The Lodash for React.
This article will show a different way to create React components. We’ll discuss responsibilities, HOCs, functional components and Recompose.
In React’s world, we have different patterns and ways to structure folders, files and manage responsibility. As our father showed us:
Okay, I give in. I wrote a guide on the most scalable file structure for React projects. I’m using it every day. Best part: it works for Vue projects too. Hope it’s helpful! ✨ https://t.co/O2mNVx7vCs— Dan Abramov (@dan_abramov) August 8, 2018
One of the most common patterns is dividing your component into presentation and behavior. The first part will be responsible for the presentation and the looks of it, and the second for how you interact with them. This pattern was introduced by Dan Abramov and it’s known as https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0, or https://medium.com/@thejasonfile/dumb-components-and-smart-components-e7b33a698d43.
Higher-Order Components, are functions that accept a component as an argument and return a new one with the changed behavior. If you already used libraries like react-redux or react-router, you’re probably acquainted with the HOCs
“Reuse behavior through different components.”
These are components without local state or lifecycle and all their data is provided by properties. You can take a look at this post to understand the pros and cons of functional components.
“Each component must be ease to test, without mock or unnecessary changes.”
Here are some of the more important HOCs:
This HOC allow us to add a state and a method to manipulate this state and an initial value. Everything will be available through properties.
This HOC is used to add event handlers, preventing the creation of new ones for each render of the component.
This HOC give us access to the lifecycle method of the component. Any state changes will be available through the properties.
This HOC is perfect to work with conditional rendering, receiving one method to test the condition and two components to render for each condition.
This HOC, group components by the same context. It’s perfect to create interfaces like atomic design with molecules and organisms.
This HOC maps all of the properties from the component and transforms them into a new collection. It’s great to work with derived properties.
Hey, what did you think about this method of development? You want to go deep and search more? The documentation is always a good start. As a complement, the talk about Recomposing React application can give you a solid base, but remember that practice by coding is always the best way to understand.
All examples are in codesandbox, where you can change and see your changes in real-time. I made this presentation with more details about the subject. Any doubts or questions? Please leave a comment and share them with us.