DEV Community

Brendan Carney
Brendan Carney

Posted on

Two Components are Better than One

Component based libraries like React are great in part because they allow us to encapsulate a piece of UI, and reuse it across our application. This allows us to have consistent UI, and makes tweaking styles easy. But, reusability can be taken too far. It might be tempting to only have one Button in your component library that can handle everything, but you can easily end up with something like:

<Button
  icon="gear"
  iconPosition="left"
  size="small"
  variant="outline"
  isLoading
  fullWidth
  {...andManyManyMore}
/>

What was once a simple Button now has props for every imaginable use case), making it hard to maintain or change.

Sometimes, it's better to have a few more components for specific use cases instead of one component that handles everything. Here are a few examples where I've created multiple components instead of adding more props to one:

Instead of a Button that can have text or just an icon, create a normal Button and a separate IconButton. This way, you won't have to special case spacing when there is text with an icon, and you can easily build an API that forces you to add a label for accessibility in your IconButton.

Instead of a SelectMenu component that can handle both single selection and multiple selection, split into SelectMenu and MultiselectMenu. The logic around these is different enough that maintenance and styling is much simpler when they are kept separate.

What are some other examples of components trying to do too much?

Top comments (0)