ReactMedium

What is HOC (Higher-Order Component)?

A higher-order component is a function that takes a component and returns a new component that wraps it with extra behavior or props, such as withAuth(Dashboard) or withTheme(Button). It was the main pattern for reusing logic before hooks; today custom hooks are preferred, but HOCs still appear in libraries and for cross-cutting wrappers.

Shape

const withX = (Wrapped) => function WithX(props) { const extra = ...; return <Wrapped {...props} extra={extra} />; }

Classic uses

  • Injecting data or behavior: Redux's old connect(), withRouter, withTranslation.
  • Guards: withAuth redirecting unauthenticated users.
  • Instrumentation: withErrorBoundary, withProfiler, logging.
  • React.memo and forwardRef are built-in functions with an HOC-like shape.

Drawbacks

  • Wrapper hell: many nested wrappers in DevTools.
  • Prop collisions: two HOCs injecting the same prop name.
  • Indirection: hard to see where a prop comes from.
  • Static methods and refs need manual forwarding (refs are simpler in React 19 because ref is a regular prop).
  • TypeScript typing of injected props is awkward.

Hooks instead

const user = useAuth() inside the component is explicit, composable and easy to type.

When HOCs still make sense

  • Wrapping components you do not control with a boundary or provider.
  • Libraries that must support class components.
  • Applying the same wrapper to many route components declaratively.

Rules

Create HOCs outside render (calling withX(Component) during render creates a new component type each time, remounting the subtree), set a displayName for DevTools, and pass through unrelated props.

Code example

tsx
1import { ErrorBoundary } from "react-error-boundary";
2import { useEffect } from "react";
3
4// HOC: add an error boundary and page-view logging to any page component
5export function withPage<P extends object>(Page: React.ComponentType<P>, pageName: string) {
6 function WrappedPage(props: P) {
7 useEffect(() => {
8 console.log("page_view", pageName);
9 }, []);
10 return (
11 <ErrorBoundary fallback={<p>{pageName} failed to load.</p>}>
12 <Page {...props} />
13 </ErrorBoundary>
14 );
15 }
16 WrappedPage.displayName = `withPage(${Page.displayName ?? Page.name})`;
17 return WrappedPage;
18}
19
20function Settings({ userId }: { userId: string }) {
21 return <h1>Settings for {userId}</h1>;
22}
23
24// Created once at module level, not during render
25export const SettingsPage = withPage(Settings, "Settings");
26
27// Hook alternative for logic reuse:
28// function usePageView(name: string) { useEffect(() => console.log("page_view", name), [name]); }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app