← React Beginner Questions - Set 3 Q28

What is a Higher-Order Component (HOC)?

React Beginner Questions - Set 3

A function that takes a component and returns a new one. It is the pre-hooks way to share behaviour, and it still appears in libraries.

Example

function withAuth(WrappedComponent) {
  return function Authenticated(props) {
    const { user } = useCurrentUser();
    if (!user) return <p>Please sign in</p>;
    return <WrappedComponent {...props} user={user} />;
  };
}

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

const ProtectedDashboard = withAuth(Dashboard);

// Conventions: prefix with "with", pass props through, never mutate
// the wrapped component, and set a displayName for DevTools.

What to notice

← Back to the question list