Ray Lee
Ray Lee

Reputation: 197

Should containers in React be reusable?

I have two containers, where most components of them are same but some are not. So I extract same components into a new container and use if-else to give them their unique components. Is this a good way to deal with containers? To clarify, I add below code.

// container A has below components
<Component1 data={dataA1} style={style} />
<Component2 data={dataA2} />
<Component3 data={dataA3} />

// container B has below components
<Component1 data={dataB1} style={style} />
<Component2 data={dataB2} />
<Component4 data={dataB4} />

// A and B have same components, so I made a new container C
<Component1 data={is this container A ? dataA1 : dataB1} style={style} />
<Component2 data={is this container A ? dataA2 : dataB2} />
is this container A ? <Component3 data={dataA3} /> : <Component4 data={dataB4} />

I feel like this is not good, though it has something reused. And if we have another container, this structure will be too unreadable and hard to maintain because of too many uses of if-else.

So what do you think about this situation? Any comments are appreciated and welcome. Thanks.

Upvotes: 2

Views: 1135

Answers (1)

jony89
jony89

Reputation: 5367

Every component should be reusable, that's one of the reason why it has been created that way.

But reuse has a cost, which is coupling.

Probably your container will not end up with data difference only, they will have different logic, will dispatch different functions or call different API.

If data is the whole difference for sure, create a factory for these components which will receive the container/data and return the appropriate component. (see factory method design pattern)

Otherwise, I would totally create different components for that.

Upvotes: 2

Related Questions