Skip to content

Higher Order Component In ReactJS

Posted on:February 19, 2024 at 12:05 PM

Table of contents

Open Table of contents

Higher Order Function

To understand higher order component in react js, we first need to understand what is higher order functions are

Let’s try to understand Higher order functions in javascript.

Higher order functions are functions which take one or more functions as an arguments and return new function.

map, filter, reduce are some of the common in built higher order functions in javascript.

How to create your own Higher order function

Let’s take an example.

Let’s say we want to get evens numbers from array.

function getEvenNumbersFromArr(arr) {
  let res = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] % 2 === 0) {
      res.push(arr[i]);
    }
  }
  return res;
}
getEvenNumbersFromArr([1, 2, 3, 4, 5, 6]);

Now we want to get odd numbers from array

function getOddNumbersFromArr(arr) {
  let res = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] % 2 !== 0) {
      res.push(arr[i]);
    }
  }
  return res;
}
getOddNumbersFromArr([1, 2, 3, 4, 5, 6]);

As you can see we are repeating for loop here. It is a violation of Don’t repeat yourself principle. With HOCs you can avoid code duplication and write more modular applications.

Let’s try to improve the above code.

const isEven = num => {
  return num % 2 === 0;
};

const isOdd = num => {
  return num % 2 !== 0;
};

// Higher Order function
function getOddEvenNumber(arr, callback) {
  let res = [];
  for (let i = 0; i < arr.length; i++) {
    if (callback(arr[i])) {
      res.push(arr[i]);
    }
  }
  return res;
}

getOddEvenNumber([1, 2, 3, 4], isEven);

Now you have understood what are HOCs, Let’s try to understand what are Higher Order Components.

Higher Order Component

A HOC is a simple JavaScript function which accepts a component or another js function and returns a completely new enhanced component based of the first one.

The HOCs are nothing more than a way of reusing code to create cleaner and simpler React components.

Let’s try to learn HOC using example. Let’s say you have want to display list of products using cards components and using table components. First thing comes to our mind is to create two components and inside components we call the api and return some data and display some data. But here we are repeating some code. To avoid this we can use HOC.

To build HOC functionality we should remember three things.

  1. create HOC function
  2. create Table component
  3. create Cards component

HOC function has three parts.

  1. create a component which takes component as an argument
  2. create a component inside HOC component, do some repeating code and return component which comes from an argument
  3. return inner component
// WithFetch.js
import { useEffect, useState } from "react";

function WithFetch(WrappedComponent) {
  const WithFetch = () => {
    const [products, setProducts] = useState([]);

    useEffect(() => {
      // fetching api
      try {
        fetch("https://reqres.in/api/users?page=2")
          .then(res => {
            return res.json();
          })
          .then(data => {
            setProducts(data.data);
          });
      } catch (error) {
        console.log(error);
      }
    }, []);

    return <>{products.length > 0 ? <WrappedComponent /> : null}</>;
  };

  return WithFetch;
}

export default WithFetch;

How to use HOC component ? import HOC function and wrap the component with HOC

// UserCards
import WithFetch from "./withFetch";

function UserCards({ users }) {
  return (
    <>
      <div>User lists with HOC functions</div>
      {users.map(user => {
        return <UserCard user={user} />;
      })}
    </>
  );
}

export default WithFetch(UserCards);

// UsersTable

import WithFetch from "./withFetch";

function UserTables({ users }) {
  return (
    <>
      <div>User lists with HOC functions</div>
      {users.map(user => {
        return <UserTable user={user} />;
      })}
    </>
  );
}

export default WithFetch(UserCards);

Common Use Cases: