When I work with clients on their React applications, I often encounter convoluted React components. Such overly complex components happen, because they have too many responsibilities â whereas one responsibility translates to one feature and one feature translates to multiple React Hooks and event handlers . Thus, when having more than one responsibility, the component becomes convoluted with too many hooks and handlers.
Letâs take for example the following React component:
How many responsibilities/features do you count? The Users component takes care of 4 things:
Everything that ends up between the component definition and the final return statement â e.g. handlers and hooks â convolutes the component and makes it more complex. This is just a minimal example to illustrate the issue, however, I have encountered components with more than 1000 lines of code. Itâs a nightmare for every developer who has to step through these components.
So how do we fix this issue? I call it extracting functionality with so-called mediator components . Taking the previous example, one could say that the Users component is tightly coupled to a specific domain (e.g. user domain) whereas the Search and Table components are reusable components which are most likely used by other domain components too.
Now, a mediator component would fit between the domain-driven and reusable components . For example, a domain specific table component would be the best approach to simplify the previous component:
Afterward, the Users component could use this new domain specific (specialized) table component:
Finally, the top-level domain specific Users component got simplified: it only cares about 2 out of 4 things â data fetching and conditional rendering â while the UserTable takes care of the rest. The Table component, while being a reusable component, receives all of its domain specific props from the UserTable component as mediator.