A Higher Order Component (HOC) is an advanced pattern in React.
It is a function that takes a component and returns a new component with additional props, logic, or functionality.
Think of HOC as a wrapper that adds behavior to a component.
🔁 Syntax:
const EnhancedComponent = higherOrderComponent(WrappedComponent);
🎯 Purpose of HOCs:
- Code reuse and abstraction
- Cross-cutting concerns like authentication, loading, logging, etc.
- Was widely used before Hooks (like
useEffect,useContext) were introduced
🧪 Example 1: Adding a Loading State
// HOC to handle loading state
const withLoading = (WrappedComponent) => {
return function EnhancedComponent({ isLoading, ...props }) {
if (isLoading) {
return <p>Loading...</p>;
}
return <WrappedComponent {...props} />;
};
};
// Regular component
function UserList({ users }) {
return (
<ul>
{users.map((u) => (
<li key={u.id}>{u.name}</li>
))}
</ul>
);
}
// Wrapped with HOC
const UserListWithLoading = withLoading(UserList);
// Usage
<UserListWithLoading isLoading={true} users={[]} />
🧪 Example 2: Authentication HOC
const withAuth = (WrappedComponent) => {
return function AuthComponent(props) {
const isLoggedIn = localStorage.getItem("token");
if (!isLoggedIn) {
return <p>Please log in to continue.</p>;
}
return <WrappedComponent {...props} />;
};
};
function Dashboard() {
return <h2>Welcome to Dashboard</h2>;
}
const ProtectedDashboard = withAuth(Dashboard);
🧠 Important Notes:
- HOCs do not mutate the original component.
- Common naming convention:
withFeatureName(e.g.,withAuth,withLogger) - Can compose multiple HOCs for powerful abstraction.
❌ Pitfalls:
- Props collisions
- Over-nesting or "wrapper hell"
- Harder to debug compared to hooks
✅ Alternatives Today:
- React Hooks: More popular and readable for logic reuse
- Custom hooks are the modern replacement for most HOC use cases.