JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext
react
senior
patterns

What are Higher-Order Components (HOCs) in React, and why are they less commonly used today?

hoc
higher-order-components
patterns
composition
hooks
reusability
Quick Answer

A Higher-Order Component is a function that takes a component and returns an enhanced component with additional props or behavior; they're less common now because React Hooks provide a cleaner solution for logic reuse without wrapper components.

Detailed Explanation

What is an HOC?

  • A function that takes a component and returns a new enhanced component
  • Pattern borrowed from higher-order functions
  • Used for cross-cutting concerns (auth, logging, theming)

Common Use Cases:

  • Authentication gates (withAuth)
  • Loading states (withLoading)
  • Data fetching (withData)
  • Theming (withTheme)
  • Analytics (withTracking)

Problems with HOCs:

  1. Wrapper hell - Multiple HOCs create deep nesting
  2. Props collision - HOCs may overwrite each other's props
  3. Hidden dependencies - Unclear where props come from
  4. Ref forwarding issues - Requires React.forwardRef
  5. Static method loss - Must be manually hoisted

Why Hooks are Preferred:

  • No extra component layers in tree
  • Clear, explicit dependencies
  • Work naturally with refs
  • Easier to compose and test
  • No props namespace collisions

When HOCs Still Make Sense:

  • Wrapping third-party components
  • Legacy class component codebases
  • Cross-cutting concerns across many components
  • Library integrations (older React Router)

Code Examples

Basic HOC pattern
// HOC that adds loading state
function withLoading(WrappedComponent) {
  // Return a new component
  return function WithLoadingComponent({ isLoading, ...props }) {
    if (isLoading) {
      return <div className="spinner">Loading...</div>;
    }
    return <WrappedComponent {...props} />;
  };
}

// Usage
const UserListWithLoading = withLoading(UserList);

function App() {
  const [loading, setLoading] = useState(true);
  const [users, setUsers] = useState([]);
  
  return (
    <UserListWithLoading 
      isLoading={loading} 
      users={users} 
    />
  );
}

Resources

React Legacy Docs - Higher-Order Components

docs

Why React Hooks over HOCs

article

Related Questions

Explain common React patterns: Compound Components, Render Props, and Custom Hooks.

senior
patterns

What are custom hooks and how do you create them?

mid
hooks
Previous
Explain common React patterns: Compound Components, Render Props, and Custom Hooks.
Next
What is Redux and Redux Thunk, and how do they manage application state and async operations?