Higher-Order Components (HOCs)

5 questions found

What is a higher order component in React?

Intermediate
A higher order component, often shortened to HOC, is a function that takes a component as input and returns a new, enhanced component with extra behavior added, without changing the original component's own code.
function withLoading(WrappedComponent) {
  return function EnhancedComponent({ isLoading, ...props }) {
    if (isLoading) return <p>Loading</p>;
    return <WrappedComponent {...props} />;
  };
}

const ProductListWithLoading = withLoading(ProductList);
Real-world example A team wraps several different components with the same withLoading higher order component, giving each one the exact same loading spinner behavior without repeating that logic inside every single component.

Common follow-ups: How has the popularity of higher order components changed since custom hooks were introduced?;What naming convention is commonly used for higher order components?

Custom Hooks;Design Patterns in React

How would you use a higher order component to add authentication protection to a page?

Intermediate
A withAuth higher order component can check whether a user is logged in, and either render the actual protected page or redirect them to a login page instead. This lets you protect many different pages using the exact same wrapping logic.
function withAuth(WrappedComponent) {
  return function ProtectedRoute(props) {
    const { user } = useAuth();
    if (!user) return <Navigate to="/login" />;
    return <WrappedComponent {...props} />;
  };
}

const ProtectedDashboard = withAuth(Dashboard);
Real-world example An admin panel wraps every sensitive page, like billing and settings, with the same withAuth higher order component, so a user who is not logged in is automatically redirected to the login page instead of seeing protected content.

Common follow-ups: How would you achieve the same protection using a custom hook instead of a higher order component?;What happens if you wrap a component with multiple higher order components at once?

Routing;Custom Hooks

What are the downsides of higher order components that led many developers to prefer custom hooks instead?

Advanced
Wrapping a component in several higher order components can create a confusing nested structure, sometimes called wrapper hell, making it harder to trace where a certain prop actually comes from. Custom hooks solve the same reuse problem more simply, since they do not add extra layers of components and their logic is easier to follow directly inside the component using them.
// Wrapper hell, hard to trace where props come from
const Enhanced = withAuth(withLoading(withTheme(Dashboard)));

// Custom hooks, flatter and easier to follow
function Dashboard() {
  const { user } = useAuth();
  const { isLoading } = useLoading();
  const theme = useTheme();
  // ...
}
Real-world example A team refactors an old component wrapped in four different higher order components into a single function component using four custom hooks instead, making the logic much easier for new developers to follow.

Common follow-ups: Are higher order components now considered outdated, or are there still good reasons to use them?;How would you convert an existing higher order component into an equivalent custom hook?

Custom Hooks;Design Patterns in React

How do you properly pass through extra props when writing a higher order component?

Intermediate
You spread any extra props received by the wrapper component down onto the wrapped component, ensuring the wrapped component still receives everything it normally would, plus whatever new prop the higher order component adds.
function withExtraData(WrappedComponent) {
  return function Enhanced(props) {
    const extraData = useExtraData();
    return <WrappedComponent {...props} extraData={extraData} />;
  };
}
Real-world example A higher order component that adds analytics tracking data still correctly passes along every other prop the original component expected, like a title or an onClick handler, thanks to spreading the original props through.

Common follow-ups: What happens if a higher order component accidentally overwrites a prop with the same name?;How would you rename the extra prop to avoid a naming collision?

Props & State;Component Composition & Children Props

What is a simple example of a higher order component that adds a border style to any component?

Beginner
A very simple higher order component can wrap any component in a div with a specific style, giving every wrapped component the same visual treatment without needing to add that styling code inside each individual component.
function withBorder(WrappedComponent) {
  return function BorderedComponent(props) {
    return (
      <div style={{ border: '2px solid gray', padding: '10px' }}>
        <WrappedComponent {...props} />
      </div>
    );
  };
}

const BorderedCard = withBorder(Card);
Real-world example A design system adds a consistent border and padding around several different card components using one shared withBorder higher order component, keeping the visual style consistent everywhere it is used.

Common follow-ups: How would you make the border color customizable instead of hardcoded?;Could this same border behavior be achieved more simply using plain component composition?

Styling in React (CSS Modules Styled Components & Tailwind);Component Composition & Children Props