Skip to main content

Command Palette

Search for a command to run...

32) Higher Order Components (HOC)

Updated
View as Markdown
  1. A Higher-Order Component (HOC) in React is an advanced pattern used to reuse component logic. Instead of duplicating logic across multiple components, you wrap a component with a function that enhances it.
    A Higher-Order Component is a function that takes a component and returns a new component.

    const EnhancedComponent = higherOrderComponent(WrappedComponent);
    

    It doesn’t modify the original component — it creates a new enhanced version.
    Why use HOCs?
    i) Reuse logic across components
    ii) Keep components clean and focused
    iii) Separate concerns (UI vs logic)
    iv) Avoid code duplication
    Real-World Use Cases
    i) Authentication (withAuth)
    ii) Authorization (withRole)
    iii) Logging
    iv) Data fetching
    v) Theming

  2. Example
    Step 1: Create a HOC

    const withLoading = (Component) => {
      return function EnhancedComponent({ isLoading, ...props }) {
        if (isLoading) {
          return <p>Loading...</p>;
        }
        return <Component {...props} />;
      };
    }
    

    Step 2: Use the HOC

    const UserList = (props) => {
      return (
        <ul>
          {props.users.map(user => <li key={user.id}>{user.name}</li>)}
        </ul>
      );
    }
    
    const UserListWithLoading = withLoading(UserList);
    

    Step 3: Render

    <UserListWithLoading isLoading={true} users={[]} />