Higher Order Components (HOC)

React js 9 min min read Updated: Feb 19, 2026 Advanced

Higher Order Components (HOC) in React js

Advanced Topic 6 of 15

Higher Order Components (HOC) in React JS - Complete Detailed Guide

When we start building real-world React applications, we quickly notice that certain logic keeps repeating. For example: authentication checks, loading states, API data fetching, logging, permission handling, theme injection, etc. Instead of writing the same logic again and again inside multiple components, React gives us a powerful pattern called Higher Order Components (HOC).


1. What is a Higher Order Component?

A Higher Order Component (HOC) is an advanced technique in React used for reusing component logic. It is not a React API. It is simply a JavaScript function.

In simple words:

A Higher Order Component is a function that takes a component as input 
and returns a new enhanced component as output.

If you understand higher order functions in JavaScript (like map, filter, reduce), then HOC is the same concept applied to components.

Command

const EnhancedComponent = higherOrderComponent(OriginalComponent);

The HOC wraps the original component and adds extra features without modifying the original component code.


2. Why Do We Need HOC?

Let's understand with a real-world situation.

Suppose you have 5 different pages in your application:

  • Dashboard
  • Profile
  • Settings
  • Orders
  • Admin Panel

All of them should only be accessible if the user is logged in.

Instead of writing this logic inside every component:

Command

if (!isLoggedIn) {
  return <Redirect to="/login" />;
}

You can create a reusable wrapper (HOC) that handles authentication logic once and apply it wherever needed.

This improves:

  • Code reusability
  • Clean architecture
  • Separation of concerns
  • Maintainability

3. Basic Example of HOC

Step 1: Create a simple component
Command

function Welcome(props) {
  return <h3>Hello {props.name}</h3>;
}
Step 2: Create a Higher Order Component
Command

function withGreeting(WrappedComponent) {
  return function EnhancedComponent(props) {
    console.log("Component rendered");
    return <WrappedComponent {...props} />;
  };
}
Step 3: Use the HOC
Command

const EnhancedWelcome = withGreeting(Welcome);

<EnhancedWelcome name="Sanjeev" />

Now whenever EnhancedWelcome renders, it will log a message and then render the original Welcome component.


4. Practical Example - Authentication HOC

Now let's create a more practical example which checks whether a user is logged in.

Authentication HOC
React Js

import React from "react";
import { Navigate } from "react-router-dom";

function withAuth(WrappedComponent) {
  return function AuthComponent(props) {

    const isLoggedIn = localStorage.getItem("token");

    if (!isLoggedIn) {
      return <Navigate to="/login" />;
    }

    return <WrappedComponent {...props} />;
  };
}

export default withAuth;
Usage
React Js

function Dashboard() {
  return <h4>Welcome to Dashboard</h4>;
}

export default withAuth(Dashboard);

Now Dashboard will automatically be protected. No need to repeat authentication logic.


5. Example - Loading State HOC

Suppose you want to show a loading spinner until data is fetched.

React Js

function withLoading(WrappedComponent) {
  return function EnhancedComponent({ isLoading, ...props }) {

    if (isLoading) {
      return <h5>Loading...</h5>;
    }

    return <WrappedComponent {...props} />;
  };
}
Usage
React Js

function UserList({ users }) {
  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

const UserListWithLoading = withLoading(UserList);

6. Important Concept - Passing Props Correctly

Whenever you create a HOC, you must pass all received props to the wrapped component using:

React Js

<WrappedComponent {...props} />

If you forget this, your component may not receive its required data.


7. Real-World Use Cases of HOC

  • Authentication & Authorization
  • Role-based access control
  • Data fetching wrapper
  • Error boundary wrapper
  • Logging & analytics tracking
  • Theme injection
  • Permission management

8. Advantages of HOC

  • Code reuse without duplication
  • Cleaner component structure
  • Separation of business logic and UI
  • Easy to test and maintain
  • Encapsulation of cross-cutting concerns

9. Limitations of HOC

  • Wrapper nesting can make debugging harder
  • Can create “wrapper hell” if overused
  • Prop name conflicts may happen
  • Less readable compared to modern Hooks

10. HOC vs Hooks

In older React versions, HOC was the main solution for logic reuse. After React Hooks were introduced, many developers prefer hooks.

However:

  • HOC is still useful for wrapping components globally.
  • Hooks are better for internal reusable logic.

Both are valid patterns depending on use case.


11. Best Practices When Writing HOC

  • Always pass props properly
  • Keep HOC focused on a single responsibility
  • Avoid modifying original component
  • Use descriptive naming like withAuth, withLoading, withTheme
  • Set displayName for easier debugging
Example with displayName
React Js

function withLogger(WrappedComponent) {
  function EnhancedComponent(props) {
    console.log("Rendering:", WrappedComponent.name);
    return <WrappedComponent {...props} />;
  }

  EnhancedComponent.displayName = 
    `withLogger(${WrappedComponent.displayName || WrappedComponent.name})`;

  return EnhancedComponent;
}

12. Final Summary

Higher Order Components are a powerful and practical pattern in React. They help you write cleaner, reusable, and maintainable code by separating common logic from UI components.

Even though modern React projects use Hooks more often, HOC is still widely used in enterprise-level applications, especially for authentication, permissions, and global wrappers.

If you understand this pattern clearly, it will improve your React architecture skills and help you write scalable applications.


That's everything you need to understand Higher Order Components in React with practical examples and real-world usage.

What People Say

Testimonial

Nagmani Solanki

Digital Marketing

Edugators platform is the best place to learn live classes, and live projects by which you can understand easily and have excellent customer service.

Testimonial

Saurabh Arya

Full Stack Developer

It was a very good experience. Edugators and the instructor worked with us through the whole process to ensure we received the best training solution for our needs.

testimonial

Praveen Madhukar

Web Design

I would definitely recommend taking courses from Edugators. The instructors are very knowledgeable, receptive to questions and willing to go out of the way to help you.

Need To Train Your Corporate Team ?

Customized Corporate Training Programs and Developing Skills For Project Success.

Google AdWords Training
React Training
Angular Training
Node.js Training
AWS Training
DevOps Training
Python Training
Hadoop Training
Photoshop Training
CorelDraw Training
.NET Training

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators