Higher Order Component (HOC) Pattern

Overview

Higher Order Components (HOCs) are a pattern in React for reusing component logic. HOCs are functions that take a component as an input and return a new enhanced component with additional props or behavior. This pattern was popular before hooks were introduced and is still useful for cross-cutting concerns like logging, authentication, and more.

Example

Below is a simple component wrapped with a logging HOC. Check your browser console to see the log messages when the component mounts, receives props, and updates.

Hello, React Developer!

Code Implementation

// withLogging.tsx
import React, { ComponentType, useEffect } from "react";

// Higher Order Component that adds logging
export function withLogging<P extends object>(
  WrappedComponent: ComponentType<P>
) {
  // Return a new component with the same props
  const WithLogging = (props: P) => {
    useEffect(() => {
      // Log when component mounts
      console.log(`[Logging HOC] ${WrappedComponent.displayName || WrappedComponent.name || 'Component'} mounted`);
      
      // Log when component will unmount
      return () => {
        console.log(`[Logging HOC] ${WrappedComponent.displayName || WrappedComponent.name || 'Component'} will unmount`);
      };
    }, []);

    // Log props on each render
    console.log(`[Logging HOC] ${WrappedComponent.displayName || WrappedComponent.name || 'Component'} rendered with props:`, props);
    
    // Render the wrapped component with its props
    return <WrappedComponent {...props} />;
  };

  // Set a display name for better debugging
  WithLogging.displayName = `WithLogging(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;
  
  return WithLogging;
}

// Usage:
// const EnhancedComponent = withLogging(MyComponent);

Key Benefits

  • Reuse component logic across many components
  • Keep cross-cutting concerns separate from component implementation
  • Add functionality to components without modifying their code (open-closed principle)
  • Composition-based approach to enhancing components
  • Useful for instrumentation, tracking, authentication, and other cross-cutting concerns