How you can choose what goes in what component? 🧐

We've talked a lot about component this, component that. But, a question I often get is ... Yes, not from you Kiwi ... How do you decide what to put in a component? When should a component be split up into multiple components? When should multiple components be combined into one component? And well, the real answer is that it depends. It's something that you're going to develop a gut feeling for, because it's really a matter of taste. But, there's a couple of guidelines that I like to use to make these decisions.

The box principle, where you kind of look at your page and decide, okay, these are kind of the squares. The second is, are components similar to each other, and can you extract them using the same extractions? And the third one is, will these things develop in separate ways? If you have to use and to describe what your component does, it should be using sub component.

Let's say you have a simple interface, like a user profile. Now you can see that I drew these out as boxes. You could literally make each of these a component. Component for your avatar, component for these different feeds, so that's the first principle, the box principle. Visually, anything that's a box can be its own component.

We had avatars here, and we had Instagram images here. So you can make an image component the same for both of them, just get some sort of image prop that tells it which you are [inaudible 00:01:16] to render. This is a great example of a reusable component that you can use in multiple places. But, a feed item, an image, some text and a date. It gets a little tricky, because you might have to pass in props to style it. So you would have a feed item of different types.

It seems like a good idea at first to have similar components and just pass in a proper that says behave a little differently this time. This is a trap. So, I would separate those, or at least have a higher level API that says Instagram feed item, personal feed item, or something like that. These things often look the same when you're starting out, but then they diverge and they evolve in different directions. Props balloon, you start adding more and more stuff in, it means you need to have a different component.

This is a warning. As soon as you say, "This is a feed item, and an Instagram item," that's when you need to split it up. Where components can merge is when they represent similar things. When they are doing the same thing, you should merge them together. Refactor, refactor, refactor.

Know someone who wants to learn React and its whole ecosystem? Share 👇


Cheers,
~Swizec