All you need to know about Higher Order Components in React

Posted by

The concept of Higher Order Component (HOC) in React is an advanced technique that is used in reusing the component logic. It is still very popular and widely used in the modern React world and the reason behind it is that it can be used both in Functional components and Class components. The concept of this component is very simple. Let me assume that you have already familiar with the Higher Order Functions in JavaScript, where we can pass a function inside a function. The concept of Higher Order Component (HOC) in React is quite similar to this.

In this tutorial, you are going to learn the most interesting topic of React and we are going to explore what is Higher Order Component? Why do we need to use this Component? and, finally, how we can use this component in our React application with an example. At the end of this tutorial, you will be able to use this component in your application.

Things You will learn from this tutorial

We will cover the following topics in this tutorial and the topic’s names are given in the below section:

  • The necessity of the Higher Order Component
  • The Higher Order Component
  • Conclusion

The necessity of the Higher Order Component

Before working with the Higher Order Component (HOC) in react, I would like to give you an idea about the necessity of this component. In simple terms, if we can create components and work with them then why this concept or technique has been introduced in React? We need to find out the answer to this question. If we don’t know the need or the actual cause behind using this component then our learning will not be fulfilled and we will not use this component in the right way.

Let’s say we are working on a React project and in our project requirement, our clients want to create a counter functionality where it will show how many times a user clicked on a button and also how many times a user hover on a text. Let’s quickly implement this functionality one by one in the below section:

ClickCounter Component

Let’s implement the click counter component first. Here, we keep things very simple. We will take a button and create the functionality for counting the clicked times. You may assume that we need to handle the state here. To do so we are going to use the Class Syntax Let’s see the implementation first in the below section:

//**ClickCounter Component**

import React from 'react'

class ClickCounter extends React.Component{
    state = {
        count : 0
    };

    incrementCount = ()=> {
        this.setState((prevState) => ({ count : prevState.count + 1}));
    }
    render(){
        const {count} = this.state
        return(
            <div>
                <button type= 'button' onClick={this.incrementCount}>Clicked {count} Times</button>
            </div>
        )
    }
}

export default ClickCounter

Here, at first, we have created a Class component and named it ClickCounter, and inside the render() function we have taken a <div> and created a simple <button>

Later on, we have taken a state to keep track of the count’s value and inside that state, we have taken a property named count and set the initial value Zero(0) Finally, destructured it inside the render() function and used it inside the button.

We have also taken incrementCount() to make things workable. Now, if the user clicked on the button it will increase the number one by one. Let’s implement the hover functionality in the below section:

HoverCounter Component

// HoverCounter Component

import React from 'react'

class HoverCounter extends React.Component{
    state = {
        count : 0
    };

    incrementCount = ()=> {
        this.setState((prevState) => ({ count : prevState.count + 1}));
    }
    render(){
        const {count} = this.state
        return(
            <div>
                <h1 onMouseOver={this.incrementCount}>Hovered {count} Times</h1>
            </div>
        )
    }
}

export default HoverCounter

Here, you can see that we have done almost the same thing that we did in the ClickCounter component. The only difference is we have changed our component name to HoverCounter and changed the button to <h1> Let’s import these components to our App.js file and run the program to see the output:

// App.js

import React from 'react'
import ClickCounter from './components/ClickCounter'
import HoverCounter from './components/HoverCounter'

const App = () => {
  return (
    <div>
      <ClickCounter/>
      <HoverCounter/>
    </div>
  )
}

export default App

We have simply imported these components and used them inside a div. Let’s say our user clicked on the button 5 times and hover on the text 3 times. What will happen? To see the output you may run the program and if you do so, you will see something like this:

Clicked 5 Times
Hovered 3 Times

That means our program has been working perfectly and we did not use any Higher Order Component (HOC) techniques. Then where’s the problem?

  • Now, let’s imagine, our client updates the project’s requirement and the client wants to make another functionality, where if a user press keys inside an input element it will count the number of keys pressed. To implement the functionality, again we need to write the same code and if we need to do this multiple times in our project, we will not be able to manage our code base.
  • If you notice the code of the ClickCounter and the HoverCounter component then you will be able to see that the code base is almost the same. We all know the common rule of Development which is DRY ( Do Not Repeat Yourself ) Which means do not write duplicate code for similar functionality. But here we are breaking this rule.

Now, you may understand the situation here. Even our program is working but it is not perfectly managed. Then what will be the solution to it? You may have already guessed it? The answer is we need to use the Higher Order Component and in the next section, we are going to explore it.

The Higher Order Component

According to the React official documentation, “ A Higher Order Component is a function that takes a component as a parameter and returns a new component “. Let’s understand this definition programmatically:

const NewComponent = higherOrderComponent(OriginalComponent)

here. higherOrderComponent is a function that takes the OriginalComponent and simply creates a NewComponent We will use this concept in our program to avoid those consequences that are mentioned above.

Creating Higher Order Functionality

We will simply create a folder named HOC inside the Components folder and create a file named withCounter.js It is a convention to use the with keyword while creating a Higher Order Component file. See the below code example:

// WithCounter.js

import React from 'react'

const withCounter = (OriginalComponent) => {
    class NewComponent extends React.Component{
        state = {
            count : 0
        };
    
        incrementCount = ()=> {
            this.setState((prevState) => ({ count : prevState.count + 1}));
        }
        render(){
            const {count} = this.state
            return <OriginalComponent count = {count} incrementCount={this.incrementCount}/>
        }
    }
    return NewComponent
}

export default withCounter

Here, you can see that we have taken a function named withCounter and passed a component named OriginalComponent This is a simple javaScript concept. In JavaScript, we can pass a function to another function and we have known that Higher Order Component is nothing but a Function.

Later on, we implemented the functionality that we are common in both components. Those are state and incrementCount Finally, we pass them as props inside the OriginalComponent Now, let’s refractor both the component in the below section:

//ClickCounter Component

import React from 'react'
import withCounter from './HOC/withCounter'

const ClickCounter = (props) => {
    const {count, incrementCount} = props
  return (
    <div>
        <button type='button' onClick={incrementCount}>Clicked {count} Times</button>
    </div>
  )
}

export default withCounter(ClickCounter)
// HoverCounter Component

import React from 'react'
import withCounter from './HOC/withCounter'

const HoverCounter = (props) => {
    const {count, incrementCount} = props
  return (
    <div>
        <h1 type='button' onMouseOver={incrementCount}>Hovered {count} Times</h1>
    </div>
  )
}

export default withCounter(HoverCounter)

Here, you can see that we have received our count and incrementCount functionality with the help of props and if you notice, you may be able to see that we do not repeat the code. Now, if we need to implement similar functionality for hundred times then we can easily do it. Not only this but also we can manage them easily. This thing is possible because of using the Higher Order Component technique.

Conclusion

In this whole tutorial, we have covered one of the essential topics in React which is the Higher Order Component. If you have come this far then congratulate yourself because now, you know what is Higher Order component? why do we need to use it and how we can use it?

If we wrap up this tutorial with the non-technical term then we can compare this Higher Order Component with Peter Parker where Peter Parker is the Original Component and when we pass Peter Parker in the withSuite() function then it becomes SpiderMan.

The Higher Order Component is a very powerful as well as a useful concept in React. If you understand this concept clearly then you can use this Component in your program that will reduce code duplication, create a more manageable Codebase, and so on. Finally, the purpose of this tutorial is to make you comfortable with this component. Now, all you need to do is to take this tutorial as the reference for your learning and try to explore and implement new things with this.

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *