Last updated 149 days ago by Rafael Quintanilhareact
React has always been great for reusing and composing components. That means you can write a piece of UI and simply reuse it later on. Moreover, your component can have some embedded logic that you can reuse too. Write once, and use everywhere. A big win!
But what if you want to reuse the logic only? It means that you don’t care about the UI, but you care about the behavior of the component. Can you still write it once and use it everywhere?
And the answer is… yes! React developers have designed all kinds of patterns for reusing logic, the most prominent being Higher-Order Components (HOC) and Render Props. They work and have been in use for quite a while. But still, those two approaches don’t feel quite right and have some shortcomings (which we will see soon). What could be a possible alternative?
As of React 16.8, Hooks were introduced. Hooks are a way to reuse logic across applications. You write a specific behavior (logic) and “hook” it into any component. This component now can use this logic normally.
Consider that you want to add a clock into your application. Clearly, you think, this is something very common that someone might have already developed. You find a React library that renders the clock and exposes a few props to customize its style and functionality (size, display seconds or not, frequency of update, etc). After a few tweaks, you have your component pretty similar to what you want, though not quite. Maybe you want to customize only the hours (make it bigger) or add a different color to the minutes. In the end, you wish you could just use the clock logic and style it exactly how you want.
This scenario is a great use case for Hooks. You can “hook” the “clock behavior” into a component and have the current time available. Then, you just use the time as you would use any variable declared in the scope of your component, the difference being that you don’t need to worry about it (in case you are curious, check the useClock hook that I developed and that illustrates this principle).
But before diving deeper into Hooks, let us understand the issues with the former solutions.
We have seen that React is great for reusing UI but that sometimes we might be interested only in the logic behind a component. Hooks are an answer to this demand. Let’s examine how we reused logic in the pre-Hooks era.
Probably the first pattern to be widely adopted by the React community on this matter, HOCs, solved the reusable logic problem using composition. Here is the idea: you develop a component which implements the logic and pass the computed values (for example, the current time) to the children, which have access to the values via props. Generically: