When building an app, it’s nice to have reusable components. There is nothing more satisfying than throwing together a good-looking page in a day because all the components are built and ready to use. And, building reusable React components is an important skill for a developer.
However, it’s important to follow some guidelines as you develop these components. You should build reusable components when there is logic or identical components used in two or three places. They should be developed as needed instead of “looking ahead” to behaviors that might be duplicated in the future. They should contain the majority of the state they need to do their job.
Limit duplication of behavior.
When building a new app or feature, it can be helpful to build the first components to fit the minimum amount of customization possible. For this example, think of a search button. This button will ask the server for info when clicked. At this point, the search button doesn’t need to be configurable. Later on, the app needs to ask the server for another entity. Now would be a better time to think about making a generic component. This would take the form of a button that receives the function it should call and the text it should display through props. The button only became truly generic when the app had the same behavior in two places.
Do one thing at a time.
Building reusable components too far in advance is a trap. In the search button above, it feels possible to make a generic component from the start. It’s possible to assume that the two searches will have similar behavior, but features can vary in their requirements. However, a software project constantly changes. The requirements today may make two features similar enough to use the same component. But, once it comes down to implementation, it may be faster to build two one-off components instead of one more complicated but reusable one.
When making a component reusable, try to minimize the amount of state it draws on from outside itself. A search button shouldn’t be importing the search term directly from another component. Pass them in through props. The global state shouldn’t need to track a modal and make sure it is displaying the right text. The modal should be able to make its own decisions about what should be displayed. This allows the app to reuse the component without importing extra state and creating dependencies. If the logic inside a component becomes complicated, then it may be able to be broken into different components instead of a reused one.
Reusable components are part of what makes React and software incredible. Their ability to speed up development and consolidate responsibility into one spot makes them powerful. However, to get the most value out of them, they should be used correctly and as needed. They work best when they perform a function found two or more times in an app, developed as they are needed rather than before, and when they contain their own state information.