A Higher-Order Component (HOC) is an advanced React pattern used to share and reuse logic between components. Instead of duplicating code, a HOC wraps an existing component and returns a new enhanced component.
HOCs are commonly used for concerns that affect many components in the same way, such as authentication, logging, performance tracking, permissions, and theming.
A HOC follows a predictable structure: take a component, wrap it, and return a new component with added behavior.
// Generic HOC syntax
const EnhancedComponent = higherOrderComponent(WrappedComponent);
This pattern allows React to treat the enhanced component like any normal component.
This example demonstrates a simple HOC that logs props whenever the wrapped component renders.
// HOC that logs incoming props
function withLogger(WrappedComponent) {
return function Enhanced(props) {
console.log("Props received:", props);
return <WrappedComponent {...props} />;
};
}
The wrapped component remains unchanged, while logging behavior is injected externally.
Authentication is a classic use case for HOCs. Protected components should only render if a user is logged in.
// HOC that blocks access for unauthenticated users
function withAuth(WrappedComponent) {
return function Authenticated(props) {
const isLoggedIn = localStorage.getItem("user");
if (!isLoggedIn) {
return <h4>Access Denied</h4>;
}
return <WrappedComponent {...props} />;
};
}
This keeps authentication logic separate from UI components like dashboards or profiles.
Multiple HOCs can be layered together to apply several behaviors in a clean and readable way.
// Applying authentication first, then logging
const Enhanced = withLogger(withAuth(Dashboard));
Execution happens from right to left: Dashboard → withAuth → withLogger.
A well-written HOC must always forward props, otherwise the wrapped component may break.
// Forwarding all props to the wrapped component
function withBorder(WrappedComponent) {
return function Enhanced(props) {
return (
<div style={{ border: "2px solid gray", padding: "10px" }}>
<WrappedComponent {...props} />
</div>
);
};
}
When a component is wrapped by a HOC, React renders the outer component first. The HOC executes its logic, then renders the original component with the same props plus any enhancements.
with for clarity.{...props}.displayName for easier debugging.withTheme HOC that injects a theme prop.Button component.withLogger to track renders.displayName.Goal: Understand how Higher-Order Components enable reusable, composable logic in React.