Refactor components with Recompose
Lately, we have been working on refactoring our existing higher-order components. In my previous blog, I discussed why and how we refactored our class component to functional components using hooks.
In this blog, I will discuss why and how we removed the usage of Recompose from our application, using hooks.
Disclaimer: This blog does not teach you about Higher-order components and Recompose. In order to read more about them refer :
Recompose official Github document
Higher order components
The reasons why we decided to refactor our components are:
- Recompose is discontinuing the active maintenance of this package (excluding perhaps bug fixes or patches for compatibility with future React releases), and recommending that people use Hooks instead.
- Hooks solve all the problems that recompose attempted to resolve.
For those of you who are familiar with the concept of higher-order component and why we use Recompose, you must be aware of two things
- A higher-order component is a way in React to reuse a component logic, they are a pattern that emerges from React compositional nature.
- Recompose is a React utility built for function components and higher-order components. What it means is that it’s a set of methods we can use to improve the organization, creation, and application of our higher-order components encouraging the use of functional stateless components combined with the composition of higher-order components.
Consider we want to have a button component and we want to create another button component that should have the same functionality as the original button component but also show us the count of the number of the times the button was clicked.
The example below shows how we can use Recompose to achieve this compositional behavior.
The example shows how we have reused a component and also enhancing the functionality for ButtonWithCount component
The same example can be written as:
What we have done here is that we have converted the buttonState from Recompose example to count state using useState and buttonHandler in Recompose was using withHandler , but instead in hooks example, we have written as a function. The entire logic of updating a state using the buttonHandler function is written inside a custom hook which is used in ButtonWithCount component.
In a similar way, we can either convert the remove recompose from our components using hooks and create reusable logics.
Coming soon…. Eslint configurations for our React projects.
Cheers!