What is a higher-order component (HOC) in React?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for React.js development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

A Higher-Order Component (HOC) is a function that takes a component and returns a new component with additional props or behavior. It is a pattern for reusing component logic. Convention: HOC names start with "with": function withAuth(WrappedComponent) { return function AuthedComponent(props) { if (!user) return <Redirect to="/login" />; return <WrappedComponent {...props} user={user} />; }; }. Usage: const AuthedDashboard = withAuth(Dashboard);. HOCs were the primary way to share logic before hooks. Common uses: authentication, data fetching, analytics, logging, theming. Problems with HOCs: wrapper hell (deeply nested component trees in DevTools), prop collisions (HOC and wrapped component use same prop name), opaque component origin, harder to debug. Modern alternatives: custom hooks solve most HOC use cases with less complexity. But HOCs remain useful for: adding error boundaries, adding class-component behavior to existing class components, or code-sharing with non-hook-compatible patterns.

Pro Tip

This topic has React.js-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.