The Lodash for React.
You can also read this article in Portuguese. Have a good read 🤓
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:
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 Presentational and Container, or Smart and Dumb.
Higher-Order Components — HOCs
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 connect() and withRouter().
“Reuse behavior through different components.”
Stateless Functional Components — SFC
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.
Before you go…
We have a biweekly newsletter with the best links we’ve been reading out here. Register on http://bit.ly/labcodesnews to receive it. If you liked this article, feel free to 👏👏👏 a few times, so other people can enjoy it as well. Cheers! 🍺