Higher-Order Components (HOC)

A Higher-Order Component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React's compositional nature.

Definition

An HOC is a function that takes a component and returns a new component.

JavaScript

const EnhancedComponent = withSomeLogic(OriginalComponent);          

Why use HOCs?

HOCs allow you to share common functionality across multiple components without duplicating code. Examples include adding authentication checks, data fetching, or logging to existing components.

Example: withAuthentication HOC

Imagine you want to protect certain pages so only logged-in users can see them.

JavaScript

import React from 'react';

function withAuthentication(WrappedComponent) {
  return function(props) {
    const isAuthenticated = localStorage.getItem('user'); // Simple check

    if (!isAuthenticated) {
      return <p>Please log in to view this content.</p>;
    }

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

// Usage
const Dashboard = (props) => <div>Welcome to your Dashboard!</div>;
const ProtectedDashboard = withAuthentication(Dashboard);          

Best Practices

Note: While HOCs are powerful, in many cases, Custom Hooks (introduced in React 16.8) are a cleaner alternative for logic reuse.