DEV Community

Bishal Pahari
Bishal Pahari

Posted on

Simple Introduction to Higher Order Components in React

Introduction
Have you ever heard of Higher Order Components (HOCs)? Don’t let the fancy name intimidate you! Think of them as powerful tools in React that can make your life easier when building complex applications. In this article, we’ll take a simple dive into what Higher Order Components are, why they’re useful, and how they can level up your React development skills without getting tangled in complex jargon.

So, grab your favorite beverage, settle into your comfy chair, and let’s explore the world of Higher Order Components together!

Why use Higher Order Components?
Higher Order Components offer several benefits in React development. Firstly, it helps in reusing logic across multiple components. They simplify handling common functionalities like authentication, logging, or data fetching. With HOCs, you can separate concerns and keep your components focused on their specific tasks. HOCs enable composing multiple behaviors or features into a single component effortlessly. Additionally, they make the code cleaner and easier to understand by moving complex logic out of components. This organization helps keep components focused on their main tasks, resulting in more organized and maintainable code overall

When to use Higher Order Components?
Imagine we have a dashboard, a profile page, and a settings page in our React application. Each of these pages requires the user to be logged in before accessing the content. Instead of writing authentication logic separately for each component, we can create a single Higher Order Component called withAuth that wraps around these components.

The withAuth HOC can check if the user is authenticated. If the user is authenticated, it renders the component; otherwise, it redirects the user to the login page.

This approach helps in keeping our code clean, modular, and easy to maintain. If the authentication logic needs to be updated or modified, we only need to do it in one place, inside the withAuth HOC, rather than updating it in multiple components.

Implementing Higher Order Components in your React App
I will try to explain to you the concept of Higher Order Components (HOCs) using a simple analogy that involves cookies:

Image description

Imagine you have two cookies, and you want to add chocolate chips on top of each one. Now think if you only have two cookies, it’s easy to manually place the chocolate chips on each cookie. But what if you have a hundred cookies? Doing it manually for each cookie would take forever!

This is where Higher Order Components (HOCs) come in handy. Think of the cookies as your components and the chocolate chips as some extra functionality or props you want to add to them. With a HOC, you can create a special function that automatically adds the chocolate chips to each cookie component without having to do it manually for each one. So, whether you have two cookies or a hundred, the HOC takes care of the job for you, making your life as a baker (or developer) much easier!

First, let’s create a file called App.js, which will be our entry point of our React application.

App.js

import React from "react";
import Cookie1 from "./components/Cookie1";
import Cookie2 from "./components/Cookie2";

const App = () => {
  return (
    <div>
      <h1>Cookies with Chocolate Chips:</h1>
      <Cookie1 />
      <Cookie2 />
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Now, let’s create a file called HOC.js, which will be our Higher Order Component (HOC) responsible for adding chocolate chips to our cookies.

HOC.js
We define our Higher Order Component called WithComponentChips. This function takes a WrappedComponent as input and returns an enhanced version of it. In this case, it adds functionality to track and display the number of chocolate chips added to the cookies.

import React, { useState } from "react";

const WithComponentChips = (WrappedComponent) => {
  const EnhancedComponent = () => {
    const [addChocolateChips, setAddChocolateChips] = useState(0);
    const handleChange = () => {
      setAddChocolateChips(addChocolateChips + 1);
    };
    return (
      <WrappedComponent
        addChocolateChips={addChocolateChips}
        handleChange={handleChange}
      />
    );
  };
  return EnhancedComponent;
};

export default WithComponentChips;
Enter fullscreen mode Exit fullscreen mode

Next, let’s create another file called Cookie1.js & Cookie2.js, which will represent our cookie component.

Cookie1.jsx

import React from "react";
import WithComponentChips from "../HOC";

const Cookie1 = ({ addChocolateChips, handleChange }) => {
  return (
    <div>
      <p> {addChocolateChips} 🍫 Chocolate Chips 🍫</p>
      <button onClick={handleChange}>Add Chocolate Chip</button>
    </div>
  );
};

export default WithComponentChips(Cookie1);
Enter fullscreen mode Exit fullscreen mode

Cookie2.jsx

import React from "react";
import WithComponentChips from "../HOC";

const Cookie2 = ({ addChocolateChips, handleChange }) => {
  return (
    <div>
      <p> {addChocolateChips} 🍫 Chocolate Chips 🍫</p>
      <button onClick={handleChange}>Add Chocolate Chip</button>
    </div>
  );
};

export default WithComponentChips(Cookie2);
Enter fullscreen mode Exit fullscreen mode

These files represent our individual cookie components. They receive props addChocolateChips and handleChange from the Higher Order Component. Each component displays the number of chocolate chips added and includes a button to add more chips when clicked.

Image description

The magic happens when we export the Cookie1.jsx and Cookie2.jsx components after enhancing them with the WithComponentChips HOC. By doing so, both cookies automatically gain the ability to track and add chocolate chips without us having to manually add this functionality to each one individually.

This example demonstrates how Higher Order Components (HOCs) can make it easier to add extra features to lots of components in our React app. It’s like adding chocolate chips to cookies — instead of doing it one by one, we use a special method that does it automatically for all our cookies. So, whether we have just a couple of cookies or a whole bunch, the HOC does the work for us, making our code neater and simpler to manage.

Conclusion
In this guide to Higher Order Components (HOCs) in React, we’ve learned how they make building apps easier. HOCs are like special helpers that let us add extra features to lots of components without repeating ourselves. We saw how they help keep our code organized, by separating different tasks into smaller pieces. Using a simple example with cookies and chocolate chips, we understood how HOCs work: just like adding chocolate chips to cookies, we can use HOCs to automatically add functionality to our components. Whether we have a few components or many, HOCs do the hard work for us, making our code cleaner and simpler to manage.

Top comments (0)