Home About Skills Products Work
Projects Services Experience
Learn
Tutorials Courses Blogs Resources
Contact
Tutorials · React JS

The Higher-Order Component (HOC) Pattern

The Higher-Order Component (HOC) Pattern

A Higher-Order Component (HOC) is a function that takes a component and returns a new, enhanced component. It's an older, but still valid, pattern for reusing cross-cutting logic (loading states, auth checks, analytics).

A Basic HOC: withLoading

function withLoading(WrappedComponent) {
  return function WithLoadingComponent({ isLoading, ...props }) {
    if (isLoading) {
      return <p>Loading...</p>;
    }

    return <WrappedComponent {...props} />;
  };
}

Using It

function UserList({ users }) {
  return (
    <ul>
      {users.map(u => <li key={u.id}>{u.name}</li>)}
    </ul>
  );
}

const UserListWithLoading = withLoading(UserList);

// Usage:
<UserListWithLoading isLoading={loading} users={users} />

withLoading wrapped UserList in a new component that handles the loading logic itself — UserList has no idea this logic even exists.

Auth Check Example

function withAuth(WrappedComponent) {
  return function WithAuthComponent(props) {
    const { user } = useContext(AuthContext);

    if (!user) {
      return <Navigate to="/login" />;
    }

    return <WrappedComponent {...props} />;
  };
}

const ProtectedDashboard = withAuth(Dashboard);

HOC vs Custom Hooks

In modern React, custom hooks (like useAuth()) are often more readable and composable than HOCs for most cases — they also avoid "wrapper hell" (multiple nested HOCs). Still, the HOC pattern remains relevant in some libraries (like Redux's old connect()) and for JSX-level wrapping.

Key Takeaways

  • An HOC is a function that takes a component and returns a new, enhanced component.
  • Useful for reusing cross-cutting concerns (auth, loading, logging).
  • Custom hooks are often the cleaner alternative for simple cases today.
What is React? JSX Introduction and Your First Component

What is React? JSX Introduction and Your First Component

What problem React actually solves, how JSX syntax works, and how to build your first component.

Setting Up a React App with Vite

Setting Up a React App with Vite

Set up a modern React project in seconds with Vite, and understand the resulting folder structure.

Understanding Components and Props

Understanding Components and Props

Build functional components and pass data from parent to child components using props.

Esc