- A Higher Order Component (HOC) is a function that takes a component as input and returns a new enhanced component.
- It is a pattern for reusing component logic.
- They are not part of React API, but a convention.
🔹 Syntax
const EnhancedComponent = HOC(WrappedComponent);
🔹 Example 1: Basic HOC
Suppose we want multiple components to show loading behavior.
import React from "react";
// Higher Order Component
function withLoader(WrappedComponent) {
return function EnhancedComponent({ isLoading, ...props }) {
if (isLoading) {
return <h3>Loading...</h3>;
}
return <WrappedComponent {...props} />;
};
}
// Normal Component
function UserList({ users }) {
return (
<ul>
{users.map((u, i) => (
<li key={i}>{u}</li>
))}
</ul>
);
}
// Wrap with HOC
const UserListWithLoader = withLoader(UserList);
export default function App() {
return (
<div>
<UserListWithLoader
isLoading={false}
users={["Dev", "John", "Aman"]}
/>
</div>
);
}
👉 The HOC adds loading behavior to UserList without modifying it.
🔹 Example 2: Reusing Logic (Authentication HOC)
function withAuth(WrappedComponent) {
return function EnhancedComponent(props) {
const isLoggedIn = true; // just an example
if (!isLoggedIn) return <h2>Please login first!</h2>;
return <WrappedComponent {...props} />;
};
}
function Dashboard() {
return <h2>Welcome to Dashboard 🚀</h2>;
}
const ProtectedDashboard = withAuth(Dashboard);
export default function App() {
return <ProtectedDashboard />;
}
👉 Here, withAuth ensures only logged-in users see the dashboard.
🔹 Real-world Use Cases of HOCs
✅ Code reuse & logic abstraction.
✅ Authentication checks.
✅ Adding loading spinners.
✅ Logging, analytics, performance tracking.
✅ Conditional rendering.
🔹 Advantages
- Promotes DRY principle (Don’t Repeat Yourself).
- Separates concerns (UI vs logic).
- Easy to compose multiple features.
🔹 Disadvantages
❌ Can make code harder to read if overused (wrapper hell).
❌ May introduce props conflicts.
❌ In modern React, many use cases are replaced with hooks & custom hooks.
✅ Short Interview Answer
“A Higher Order Component is a function that takes a component and returns a new enhanced component. It’s a pattern for reusing logic, commonly used for authentication, loading spinners, analytics, etc. In modern React, many HOC use cases are replaced with hooks and custom hooks.”