4 ms·
The single best piece of React knowledge I've found is an old idea from functional programming and MVC. Separation of components into 2 groups. Pure "view" comp
by elanning 5y ago
The single best piece of React knowledge I've found is an old idea from functional programming and MVC. Separation of components into 2 groups. Pure "view" components that contain no state and are oriented around display. And "controller" components that put everything together. The controller components make http requests, manage state, and manage which sub view is currently active. So far it has worked out well. Dan Abramov had a similar idea with presentational vs container components but missed a lot of the nuance that functional programming had brought, and thus, value.
- activitypea 5y agoWhat's gained from that?
- elanning 5y agoGood question. Pure view components are incredibly easy to test and reason about. State management usually gets put into hooks that the controller component uses, which are also easier to test. You can have a nice set of unit tests for the hooks and the view components, and then a few "e2e" or integration type tests for the whole thing. Separating code into groups like this can also make it easier to find things. It also lends itself to nice reusable components.
- franciscop 5y agoI have found better success personally with "presentational vs container" instead of "view vs controller" as you describe it. For example, a checkbox IMHO would be better considered a presentational component even if it manages the small bit of state it needs for it to work. Same with many of the state management that is around "visual" changes. The point where I normally decide to split it up like you say into sub-components is just when the component becomes too complex.
- elanning 5y agoYes, many have found good success with putting a minor bit of UI state into the "mostly pure" view components. It works well until some other part of the app needs to uncheck the checkbox due to some new business requirement. This is why I usually provide a nice default "useCheckbox" hook in the same file as the pure Checkbox component.
- cmwelsh 5y agoAbsolutely. The best thing I did for my React code base was to separate the entire view layer from the logic layer. That literally means I had components called e.g. UserProfileView that were stateless and unit tested, and another set of components called e.g. UserProfile that managed state. Push all your callbacks into a separate component.