A Higher-Order Component (HOC) is an advanced pattern in React for reusing component logic. Formally, a HOC is a pure function that receives a component as an argument and returns a new enhanced component.
// HOC Pattern: Function returning Function Component
const EnhancedComponent = withFeature(WrappedComponent);
withAuthentication)import React from 'react';
// HOC for Access Control Guard
export function withAuthentication(WrappedComponent) {
return function AuthenticatedComponent(props) {
const isAuthenticated = localStorage.getItem('user_token');
if (!isAuthenticated) {
return (
<div className="unauthorized">
<h3>Access Denied</h3>
<p>Please log in to view this page.</p>
</div>
);
}
// Pass all incoming props down to the wrapped component
return <WrappedComponent {...props} />;
};
}
// Target Functional Component
function SecretDashboard({ userRole }) {
return (
<div>
<h2>Confidential Dashboard</h2>
<p>User Privilege Level: {userRole}</p>
</div>
);
}
// Export Enhanced Component
export default withAuthentication(SecretDashboard);
While Custom Hooks (useAuth()) are now the modern standard for sharing stateful logic, HOCs remain useful for wrapping component trees with conditional rendering guards or cross-cutting structural behavior.
{...props} to avoid breaking component prop contracts.Write a withLoading(WrappedComponent) HOC that displays <Spinner /> if props.isLoading is true, otherwise rendering <WrappedComponent />.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With