Skip to content

React Higher-Order Components Explained — Component Enhancement Pattern

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about React Higher. We cover key concepts, practical examples, and best practices to help you master this topic.

React higher-order components (HOCs) are functions that take a component and return a new component with enhanced functionality, enabling cross-cutting code reuse.

What You'll Learn

  • What HOCs are and how they work
  • How to create HOCs for auth, logging, and styling
  • How to compose multiple HOCs
  • HOC limitations and alternatives

Why It Matters

HOCs were the primary code reuse pattern before hooks. Many legacy React codebases and libraries still use HOCs. Understanding them helps you maintain and migrate older code.

function withAuth(WrappedComponent) {
  function AuthenticatedComponent(props) {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
      fetch("/api/auth/me")
        .then(r => r.json())
        .then(u => { setUser(u); setLoading(false); })
        .catch(() => setLoading(false));
    }, []);

    if (loading) return <div>Loading...</div>;
    if (!user) return <div>Please log in</div>;

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

  AuthenticatedComponent.displayName = `withAuth(${WrappedComponent.displayName || WrappedComponent.name || "Component"})`;
  return AuthenticatedComponent;
}

function Dashboard({ user }) {
  return <h1>Welcome, {user.name}!</h1>;
}

const ProtectedDashboard = withAuth(Dashboard);

Expected output: The Dashboard only renders when the user is authenticated. The HOC handles loading and auth checks transparently.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro