Skip to main content

Lesson 3 of 8

Higher-Order Components (HOC)

HOCs are functions that take a component and return a new component with enhanced behavior. Common production uses: withAuth (protect routes), withErrorBoundary (add error handling), withLogging (analytics). HOCs are still useful for wrapping class libraries and cross-cutting concerns.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

HOC Pattern - withAuth & withErrorBoundary

HOC Pattern - withAuth & withErrorBoundary
import { ComponentType, useEffect } from 'react';
import { Navigate, useLocation } from 'react-router-dom';

// withAuth HOC - wraps any component, redirects if not authenticated
function withAuth<P extends object>(
  WrappedComponent: ComponentType<P>,
  { requiredRole }: { requiredRole?: string } = {}
) {
  function AuthenticatedComponent(props: P) {
    const { user, isLoading } = useAuth();
    const location = useLocation();

    if (isLoading) return <Spinner />;
    if (!user) return <Navigate to="/login" state={{ from: location }} replace />;
    if (requiredRole && user.role !== requiredRole) return <Navigate to="/403" replace />;

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

  // displayName for DevTools
  AuthenticatedComponent.displayName = `withAuth(${WrappedComponent.displayName ?? WrappedComponent.name})`;
  return AuthenticatedComponent;
}

// Usage
const AdminDashboard = withAuth(Dashboard, { requiredRole: 'admin' });

// withLogging HOC - fires analytics event when component mounts
function withPageTracking<P extends object>(
  WrappedComponent: ComponentType<P>,
  pageName: string
) {
  function TrackedComponent(props: P) {
    useEffect(() => {
      analytics.track('page_view', { page: pageName });
    }, []);
    return <WrappedComponent {...props} />;
  }
  TrackedComponent.displayName = `withPageTracking(${WrappedComponent.displayName ?? WrappedComponent.name})`;
  return TrackedComponent;
}

// withSuspense HOC - wraps lazy components with Suspense + fallback
function withSuspense<P extends object>(
  WrappedComponent: ComponentType<P>,
  fallback: React.ReactNode = <Spinner />
) {
  function SuspenseWrapper(props: P) {
    return (
      <Suspense fallback={fallback}>
        <WrappedComponent {...props} />
      </Suspense>
    );
  }
  return SuspenseWrapper;
}

const LazyChart = withSuspense(lazy(() => import('./Chart')), <ChartSkeleton />);

// HOC composition (right-to-left)
const EnhancedDashboard = withAuth(
  withLogging(
    withSuspense(Dashboard),
    'dashboard'
  )
);
// Equivalent: withAuth(withLogging(withSuspense(Dashboard), 'dashboard'))

HOC vs Custom Hooks - When to Use Each

  • Use HOC when: wrapping a component with lifecycle behavior that's hard to express as a hook (error boundaries), integrating with class component libraries, applied to multiple components as a decoration
  • Use custom hook when: sharing stateful logic between components is the goal (any useState/useEffect logic), the shared logic produces data not UI, better TypeScript inference is needed
  • Always set `displayName` on HOCs - without it, React DevTools shows the wrapped component name without the HOC wrapper, making debugging confusing
  • Don't define HOCs inside render - `const Enhanced = withFoo(Bar)` should be outside the component; defining inside component causes a new component class every render, breaking reconciliation
  • Forwarding refs - HOCs must use `React.forwardRef` if consumers need to place refs on the wrapped component; this is a common gotcha with HOC composition

Tip

Tip

Practice HigherOrder Components HOC in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and flow for Higher-Order Components (HOC)

Practice Task

Note

Practice Task - (1) Write a working example of HigherOrder Components HOC from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with HigherOrder Components HOC is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Key Takeaways

  • HOCs are functions that take a component and return a new component with enhanced behavior.
  • Use HOC when: wrapping a component with lifecycle behavior that's hard to express as a hook (error boundaries), integrating with class component libraries, applied to multiple components as a decoration
  • Use custom hook when: sharing stateful logic between components is the goal (any useState/useEffect logic), the shared logic produces data not UI, better TypeScript inference is needed
  • Always set `displayName` on HOCs - without it, React DevTools shows the wrapped component name without the HOC wrapper, making debugging confusing

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done