Higher Order Component (HOC) in React

Higher Order Component (HOC) in React
Spread the love

Higher Order Component (HOC) is a JavaScript function that takes a React component as input and returns a newly updated component. Using Higher Order Components in React is an advanced technique for reusing component logic.

HOC can be used for the following use cases:

  1. Code reuse, logic, and bootstrap abstraction
  2. Render high jacking
  3. State Abstraction & Manipulation
  4. Props Manipulation

HOC can be used in implementing authentication, error handling, logging, and performance tracking.

Let’s implement the React code and see how it works:

Create a new Counter component:

import {useState} from 'react';
import PropTypes from "prop-types";

function Component1() {  const [count, setCount} = useState(0)  return (
    <div>
      Component1 ${count}
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

PropTypes.propTypes = {
  count: PropTypes.number.isRequired,
  setCount: PropTypes.func.isRequired,
};

export default HOC(Component1);

If we need another Counter then we will create a new component called Component2 and create new state, where we can see the code duplication. Instead of implementing it like that, we will create a new Higher Order Component which will accept a React Node Component, and inside that HOC it will have the state and any other logics of it and return the newly modified component.

import { useState } from "react";

function HOC(Component) {
  function NewComponent() {
    const [count, setCount] = useState(0);
    return <Component count={count} setCount={setCount} />;
  }
  return NewComponent;
}

export default HOC;

So, the NewComponent function passes the state variable and the set state variable to the passed component.

Now, let’s modify Component1 to accept props and wrap Component1 with the HOC component which we wrote just before.

import PropTypes from "prop-types";
import HOC from "./HOC";

function Component1({ count, setCount }) {
  return (
    <div>
      Component1 ${count}
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

PropTypes.propTypes = {
  count: PropTypes.number.isRequired,
  setCount: PropTypes.func.isRequired,
};

export default HOC(Component1);

By wrapping up Component 1 with HOC, the HOC component takes this Component and alters it according to the implementation and returns back. Let’s create another component called Component2 and wrap it with the HOC component as we did for Component1. Now, let’s import both these components in the App.tsx file and see the result.

parathantl Avatar

Leave a Reply

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