A Higher-Order Component (HOC) in React is a JavaScript function that accepts a component as an argument and returns a new enhanced component. HOCs follow a const Enhanced = withFeature(BaseComponent) convention to share behavior—such as authentication checks, telemetry tracking, or permission guards—without repeating code inside every screen.
Unlike regular components that return JSX directly, an HOC acts as a component factory. Keep HOCs pure by returning a new component and forwarding all incoming props ({...props}) to the wrapped component.
function withAuth(WrappedComponent) {
return function AuthenticatedComponent(props) {
const isLoggedIn = Boolean(localStorage.getItem('auth_token'));
if (!isLoggedIn) {
return <p>Please sign in to view this panel.</p>;
}
return <WrappedComponent {...props} />;
};
}
function BillingSettings({ accountName }) {
return <h2>Billing settings for {accountName}</h2>;
}
export const ProtectedBilling = withAuth(BillingSettings);
Before Hooks arrived, HOCs were the main way to share stateful logic across components. Today, Custom Hooks (useAuth(), useWindowWidth()) cover almost every state and effect sharing scenario with cleaner TypeScript types and zero nested wrapper layers in React DevTools. HOCs still remain useful when you need to gate whether a component mounts at all (such as route protection wrappers) or maintain legacy libraries.
const Wrapped = withAuth(Profile) inside another component creates a brand-new component type on every render, destroying child state. Always call HOCs once at module top level.{...props} drops props supplied by the caller.WrappedComponent.prototype causes unpredictable bugs; always compose a fresh wrapper function.No, HOCs are valid JavaScript functions and still work in React 19, though Custom Hooks are preferred for sharing reusable state and effects.
Stacking multiple HOCs (withRouter(withTheme(withAuth(Page)))) creates deeply nested layers in DevTools and risks prop name collisions between wrappers.
ref automatically?In React 18, ref required React.forwardRef inside the HOC. In React 19, ref is passed as a regular prop inside {...props} automatically.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With