All topics
Patternsintermediate

Higher-Order Components (HOCs)

Learn how higher-order components wrap a component to inject additional props or behavior, and why hooks replaced most use cases.

A higher-order component (HOC) is a function that takes a component and returns a new component with additional props or behavior layered on top — conventionally named withSomething(Component). This mirrors higher-order functions in general JavaScript, applied specifically to the problem of sharing cross-cutting concerns (like injecting a theme, auth state, or data-fetching results) across many components.

An HOC is like a gift-wrapping service that takes your product (component) and wraps it in successive layers of packaging (each HOC), where each layer can add its own extra insert (injected props) — useful, but stacking many layers makes it harder to see the original product without unwrapping each one.

Key Concepts

1
HOCs were a primary logic-reuse mechanism before hooks, used heavily by libraries like older React Router (withRouter) and Redux (connect). Wrapping a component in one or more HOCs (withAuth(withTheme(MyComponent))) composes their injected behavior, but each layer adds an actual extra component instance in the React tree, which shows up in dev tools and can make debugging deeper nesting more confusing.
withRouterconnectwithAuth(withTheme(MyComponent))
2
Since hooks were introduced, most logic that used to require an HOC (data fetching, subscribing to context-like values, injecting derived props) can be expressed as a custom hook called directly inside the component that needs it, avoiding the extra wrapper nesting and making the data flow more explicit and traceable directly in the component's own code rather than injected invisibly through props by a wrapper.
3
Interviewers ask about HOCs mainly to see if a candidate recognizes them as a legacy-but-still-occasionally-relevant pattern (some libraries still expose HOC APIs, and certain cross-cutting concerns like error boundaries can't currently be expressed as hooks since hooks can't catch render errors), and can articulate concretely why hooks are generally preferred for new code.