Andrew's Digital Garden

Separating view from non-view in React

React components often contain a mix of four different responsibities:

  • Networking requests
  • Formatting data
  • Business logic
  • Rendering

In general, it's a good idea to separate these as much as possible and to not combine them in a single component. As a general guideline keep view code away from non-view code.

Hooks can be a good place to store non-view logic, and then pass that to a component like normal to render. They offer better encapsulation. Even better is regular functions and classes, as it keeps you from coupling directly to React.

Views change more frequently than on-view logic. Keeping them separate aids maintainability.

These practices:

  • Help maintainability, as it's easier to update separate parts of the code without accidentally impacting others
  • Increases modularity, as you can always pass the data to a different view and vice versa
  • Enhances readability, due to the less complexity
  • Improves scalability, for similar reasons

As always, nuance is important. For very small components it can make sense to keep everything contained in a single component.

https://martinfowler.com/articles/modularizing-react-apps.html

[[architecture]] [[engineering]] [[react]] [[refactoring]]

Separating view from non-view in React