What is a Higher-Order Component (HOC) in React?
A Higher-Order Component (HOC) is an advanced React pattern that involves a function that takes a component as an argument and returns a new component with additional props or behavior.
It’s not a feature of React itself, but a pattern based on JavaScript functions and React’s compositional nature.
Key Concept:
A Higher-Order Component is a function like this:
javascriptCopyEditconst EnhancedComponent = higherOrderComponent(WrappedComponent);
Syntax:
javascriptCopyEditfunction withExtraProps(WrappedComponent) {
return function EnhancedComponent(props) {
return <WrappedComponent {...props} extraProp="I am extra!" />;
};
}
Simple Example:
Let’s add an extra message prop to a component using HOC:
1. Create a Regular Component:
javascriptCopyEditfunction HelloComponent({ name, message }) {
return (
<div>
<h1>Hello, {name}!</h1>
<p>{message}</p>
</div>
);
}
2. Create a HOC (Higher-Order Component):
javascriptCopyEditfunction withMessage(WrappedComponent) {
return function EnhancedComponent(props) {
return <WrappedComponent {...props} message="This is a message from HOC!" />;
};
}
3. Use the HOC:
javascriptCopyEditconst EnhancedHello = withMessage(HelloComponent);
function App() {
return <EnhancedHello name="John" />;
}
Output:
csharpCopyEditHello, John!
This is a message from HOC!
When to Use HOCs:
✅ Reusing Logic: Share logic across multiple components (e.g., authentication, permissions, logging, data fetching).
✅ Props Injection: Add extra props or modify existing props.
✅ Conditional Rendering: Wrap components with conditional logic.
Real-world Use Cases:
- Authentication check: Show login screen if user is not authenticated.
- Loading Spinner: Show loading state while fetching data.
- Permission-based Access: Show content only if the user has permissions.
Benefits:
✅ Code Reusability: Extract logic from components and reuse it across the application.
✅ Separation of Concerns: Separate component logic (e.g., data fetching) from UI rendering.
Drawbacks:
🔴 Wrapper Hell: Too many nested HOCs can reduce readability.
🔴 Props Conflicts: HOCs can overwrite props, leading to unexpected behavior.
Alternatives to HOCs:
🟢 Render Props: Pass a function as a child to share behavior.
🟢 Custom Hooks (Preferred in Modern React): Encapsulate stateful logic into reusable hooks.
Summary:
Feature | Description |
---|---|
Higher-Order Component (HOC) | Function that takes a component and returns a new component with added behavior or props. |
Purpose | Code reusability, logic sharing, and props enhancement. |
Syntax | const EnhancedComponent = withHOC(WrappedComponent); |
Common Uses | Authentication, data fetching, conditional rendering. |
Alternatives | Custom Hooks (modern approach), Render Props. |
While HOCs are still valid, modern React development often favors Custom Hooks because they are simpler and more readable.