DEV Community

Discussion on: Writing clean, reusable components in React (best practices)

Collapse
 
ekeijl profile image
Edwin • Edited

Nice article! I would like to add:

  • It can be difficult to define what the responsibilities of the component are. You will need to be very strict about the API of the component (meaning what props it accepts).
  • The process of building reusable components needs to be clear for all team members. I've seen it happen that someone needs a change to a component and adds very specific business logic to an otherwise reusable component. This decreases reusability of the component.
    • The better solution is to simply create a new "specialized" component that builds on top of the reusable component, this is the strength of React and trivial to do.
    • Duplicating the component code is also an option, but not really preferred since you will have to make changes in multiple places, which can become hard to maintain.
  • I found that developing components with Storybook helps a lot, because (1) you work on the component in isolation from the app, which forces you to think about the component API more and (2) you are creating "living documentation" (changes to the code are immediately visible) that is easy to find for all team members.
  • There is a fine line between a good reusable component and something that is over-engineered and too complex to use. You can only decide yourself (based on your use case) how much you need to be able to customize your component through props. Again, often it is better to create a new component instead of adding a new feature.
    • Do you need to support custom styling through className or do you need completely headless components? Should dark mode be built in?
  • What I've learned is that if you have two options for an implementation, you should pick the one that allows you to easily make changes in the future.
    • If you are building a button that has a "danger" state, you could add an <Button isDanger={true}> prop, but it might be better to do <Button type="danger"> if you foresee multiple types being added in the future (also, having the props <Button isDanger isWarning /> does not make sense).
  • However, you should also realize that we cannot predict the future. Adding a feature "because we might need it next sprint" is a bad idea, because requirements change all the time and it leads to over-engineering.

Like I said, building reusable component is not an easy task and it takes some practise, but leads to better code quality down the line.

Collapse
 
codewithshahan profile image
Programming with Shahan

Great explanation. Its really helpful.