Script Valley
React.js: Complete Course
Component Patterns and Context APILesson 4.3

Higher-order components (HOC) pattern explained

HOC definition, wrapping pattern, withAuth example, displayName, prop forwarding, HOC vs hooks comparison, when HOCs still make sense

Higher-Order Components

A Higher-Order Component (HOC) is a function that takes a component and returns a new, enhanced component. It's a pattern for cross-cutting concerns like authentication guards, analytics, or data fetching.

withAuth HOC

import { Navigate } from 'react-router-dom';

function withAuth(WrappedComponent) {
  function AuthGuard(props) {
    const isLoggedIn = Boolean(localStorage.getItem('token'));

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

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

  // Helpful for React DevTools
  AuthGuard.displayName = `withAuth(${WrappedComponent.displayName || WrappedComponent.name})`;

  return AuthGuard;
}

// Usage
const ProtectedDashboard = withAuth(Dashboard);

Always forward all props with {...props} so the wrapped component receives everything it needs. Set displayName so the enhanced component is identifiable in React DevTools.

Custom hooks replaced most HOC use cases โ€” hooks are simpler and don't add extra DOM nesting. HOCs still make sense when you need to wrap a component with a React tree (like a Provider) rather than just inject logic.

Up next

React.memo and performance optimization for components

Sign in to track progress

Higher-order components (HOC) pattern explained โ€” Component Patterns and Context API โ€” React.js: Complete Course โ€” Script Valley โ€” Script Valley