Higher Order Components (HOC) in React js
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.
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:
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
function Welcome(props) {
return <h3>Hello {props.name}</h3>;
}
Step 2: Create a Higher Order Component
function withGreeting(WrappedComponent) {
return function EnhancedComponent(props) {
console.log("Component rendered");
return <WrappedComponent {...props} />;
};
}
Step 3: Use the HOC
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
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
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.
function withLoading(WrappedComponent) {
return function EnhancedComponent({ isLoading, ...props }) {
if (isLoading) {
return <h5>Loading...</h5>;
}
return <WrappedComponent {...props} />;
};
}
Usage
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:
<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
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.

