One of the core advantages of react is Reusing its components and before HOC what resuability technique we are using in our development?
Most common answer is create a functional or presentational component and pass down props into it from wherever we want to use it. But isn’t this limited to only presentational reusability? What about when we need to reuse a functionality involving some state variables and some methods to manipulate the state? For Example, opening a same modal on clicking a button, image and a nav-menu where all 3 are present in different components, we’ll need to maintain a modalOpen, modalClose state variable in all 3 components and the same modal code also. This is when we can use something called Higher-order components.
A higher-order component is a function that takes a component and returns a new component.
Now, Let’s see the implementation. Conside a case where you need to record number of times a user clicks a button. What you’ll do? You’ll make a component with a button and a state variable count and a method incrementCount which will increment the count whenever user clicks the button. Simple enough!
Now, create a paragraph and record how many times user hovers over it, again, we will create a state variable count and a method incrementCount and increment the count whenver user hovers over it.
Here, we are writing same code twice. Let’s see how we can solve this using HOC.
Here withCounter is a high order function which is taking a component WrappedComponent as parameter and returning NewComponent after some enhancement to WrappedComponent which is basically some props which cann be reused in muptiple components.
Real World Examples
A very common functionality is toggling. This can be used in different scenarios such as collapsing/expanding a list, showing/hiding a component, highlight/unhighlight a message to get the attention of the user etc. In this article, we will focus on two examples to better understand how HOC work and understand how to use them to our advantage.
The two examples we’ll use will be:
- Toggle between a paragraph and an input. This will allow the user to toggle between editing and viewing the title of a post.
- Toggle between a collapsed/expanded list.
Both these cases need the same functionality of toggling. Using a HOC we can write the logic of toggling once and reuse it for the same components.
To achieve this functionality we only need to keep in state a
toggleStatus key and have a function that toggles that status. Therefore the HOC will look something like this: