A higher-order component (HOC) is a function that takes a component and returns a new, enhanced component: const Enhanced = withSomething(Component). It's a pattern built on composition, not a React API. HOCs were the main way to reuse cross-cutting logic (auth guards, data subscriptions, theming, analytics) before hooks, e.g. Redux's connect and React Router's old withRouter. Today custom hooks are preferred for sharing logic. HOCs still fit when you need to wrap rendering: guards, error or Suspense boundaries, layout, or instrumenting components you don't own.
function withAuthGuard(Component, { redirectTo = '/login' } = {}) {
function Guarded(props) {
const { user, loading } = useAuth();
if (loading) return <Spinner />;
if (!user) return <Navigate to={redirectTo} replace />;
return <Component {...props} user={user} />;
}
Guarded.displayName = `withAuthGuard(${Component.displayName || Component.name || 'Component'})`;
return Guarded;
}
export default withAuthGuard(SettingsPage);
{...props}) so the HOC is transparent.displayName for DevTools and error stacks.hoist-non-react-statics).forwardRef. In 19, ref is a normal prop and passes through with {...props}.const X = withFoo(Y) inside a component makes a new component type every render, which remounts the subtree and loses all state.withRouter(connect(...)(withTheme(withStyles(Component)))) creates deep trees in DevTools.user or theme.data silently overwrite each other.Hooks address all of these: const user = useAuth() is explicit, composable and typed.
withErrorBoundary(Widget) (react-error-boundary ships one), withSuspense.memo(Component) and lazy(), which are HOC-shaped themselves.displayName, statics, refs, and never create them during render.Spotted a mistake or a rights concern? Report an issue