After gaining more and more experience using React I created myself a list with best practices. Some of them are based solely on common sense, others are a bit more technical. Today I will write about the size of components.
Avoid components that are too big
To state the obvious, smaller components means code that is easier to read and to maintain. Now it's time to wonder what big and small means in a context like this. In most cases, you can follow your instinct; you just want to avoid duplicate code. In other words, the goal is to have smaller components that you can reuse.
Even when you have certain specific code that can never be reused you should consider refactoring it in smaller components. Having a component with hundreds of lines is harder to maintain and to debug, with the result that each update of that component will take more time than necessary. This is something you want to avoid so you don't drive yourself or your colleagues crazy.
Let's have a look at an example.
After rework (read: refactoring in smaller components) we get the code below.
Danger of enthousiasm
The above is a rule of thumb, but don't got too excited either. Of course you can refactor the above example even further, but you also have to wonder if it makes sense to give each HTML element its own component. Then answer is no; you should see a component as a standalone, reusable chunk of HTML. Logical examples of components are a footer, menu, sidebar …
As said in the introduction, this is mainly about gut feeling. Decide for yourself what can be seen as a component for yourself or, if you work in a team, discuss it with each other and make clear agreements. In the end it is you who have to maintain the code, so make it pleasant for yourself.
Be sure to keep an eye on this blog as more React best practices and tips will follow soon.