Higher-Order Components

const EnhancedComponent = withHOC(BaseComponent);

Think of HOCs as decorators or wrappers. They take a component and return a powerful, upgraded version of it.

What is a HOC?

A Higher-Order Component (HOC) is a function that takes a component and returns a new component. It's a pattern for reusing component logic.

The Problem: Duplication

Imagine multiple components need the same logic (e.g., fetching data, checking authentication). Copy-pasting this logic violates DRY principles.

The Solution: Wrapping

Instead of duplicating, we create a 'wrapper' function. This HOC injects the shared logic (like loading states) into any component you give it.

Power Up: Props Proxying

HOCs aren't just for logic. They can intercept props, add new ones (like `isAdmin`), or even block them. It's like a middleware for your components.

Live Example

Here, both UserProfile and ProductCard are improved by the same `withLoader` HOC. They both get loading spinners for free!

The `withLoader` HOC

This is the standard pattern. We wrap the returned component to handle the loading state automatically.

withLoader.js
// The HOC Function
function withLoader(WrappedComponent) {
  // Returns a New Component
  return function EnhancedComponent(props) {
    const [isLoading, setIsLoading] = useState(true);

    // Shared Logic
    useEffect(() => {
      setTimeout(() => setIsLoading(false), 2000);
    }, []);

    if (isLoading) return <Spinner />;

    // Pass through original props!
    return <WrappedComponent {...props} />;
  };
}
High-Order Component Definition
App.js
// 1. Create Base Component
const UserProfile = ({ name }) => <h1>Hello, {name}</h1>;

// 2. Wrap it
const UserWithLoader = withLoader(UserProfile);

// 3. Use the Enhanced Component
<UserWithLoader name="Alice" />
Using the HOC

The Props Proxy Pattern

Here, the HOC inspects the user and injects an `isAdmin` prop. The wrapped component doesn't need to check auth logic itself; it just receives the result!

withAuth.js
function withAuth(WrappedComponent) {
  return function(props) {
    const user = useUser(); // Hook to get current user
    
    // 1. Check permissions
    const isAdmin = user.role === 'ADMIN';

    // 2. Inject new prop
    return (
      <WrappedComponent 
        {...props} 
        isAdmin={isAdmin} 
      />
    );
  };
}
Injecting Props via HOC

Ready for more patterns?

HOCs are just the beginning. Check out Render Props and Custom Hooks to complete your mastery.

Explore React Patterns
AlgoAnimator: Interactive Data Structures