For a considerable time, I worked developing components that had unnecessary props and logic. Today I want to show you how to develop flexible and maintainable components so you don’t keep doing the same mistakes I did.
The problem
Take this Card as an example, what’s wrong with this?
A lot of props, making the API complex
There’s a lot of props. So many that probably someone using this component will never use some of it.
It’s hard to maintain
For every new feature, another prop has to be passed and more logic has to be done.
Not flexible
Imagine if you want to change the position of any component, again you have to include one more prop and add more logic. You basically has to create a prop for every use case.
The solution is…
Composition. Breaking your components into multiple elements will make it way simpler.
It's flexible, customizable and maintainable
Want to change the order to have a subhead after the thumbnail? Change it. Need to customize any component inside card? Just insert a className and style it. The thing is: here you build your component the way you want, not the way the API forced you to.
When having that much of props is actually a good option
1. You’re building a component to display some fetched data.
Spreading a object will make it's keys and values to be used as props. It's practical.
2. You don’t need any flexibility or customization
There’s no significant advantage to take from composition, so it’s fine to just use props in this situation.
Conclusion
When you need flexibility in your components, take advantage of component composition. Break your component into multiple components and it will be a lot simpler to work with.
Top comments (0)