In this blog post, we are going to talk about Higher-Order Components from React. Also, known as HOC. If you are familiar with Redux, you have probably used “connect” which is one of the examples of Higher-Order Components.
What is HOC?
HOC is a function that takes a component as an argument and returns a new component. Which looks something like this:
const EnhancedComponent = higherOrderComponent(WrappedComponent)
When to use it?
Let's say you have two components. One is called “IncreaseCountOnDoubelClick” that is incrementing a number each time that a double click of a button occurs and the other is called “IncreaseCount” that also increments a number each time a different button is clicked. They both contain similar code as seen below:
In the above two code snippets from lines 4 through 13 we have some code duplication and as a developer we always try to follow DRY(do not repeat) principle. Here is where we can utilize HOC’s to allow us to put duplicated code in a single place and then share that code among components as necessary.
Below, we create a “withCounter(higherOrderFunction)” function and pass “WrappedComponent(OriginalComponent)” as an argument. Then we return an “EnhancedComponent” component that is named “WithCounter” from the function. This is our simple HigherOrderComponent. Let's extract the duplicate code in this function.
After moving the duplicate code, there are few things we have to add in WrappedComponent. In WrappedComponent, we are passing counter and increaseCount as props. One very important thing we are adding here is {...this.props}
. By doing so it will give access to any other props beside the counter and increaseCount props.
Now, we can remove duplicate code from both components and instead of exporting IncreaseOnDoubleClick or IncreaseCount, let's export our HOC. Like this:
Note: Make sure you update this.state.counter
to this.props.counter
and this.increaseCount
to this.props.increaseCount
. In Addition, make sure to add both components to App.js.
If you want to dig deeper into Higher-Order Components you can explore this react-document link.
Top comments (0)