Sub topic 4
Higher-order components
This chapter assumes you know function components, props, JSX, useState and useEffect, passing functions as props, and basic ES module syntax. It also assumes you have seen render props, which solve a similar problem.
What a higher-order component is
A higher-order component (HOC) is a function that takes a component and returns a new component. It adds behavior or data to the original without changing its source.
const EnhancedComponent = withSomething(BaseComponent);The name comes from higher-order functions, which take or return other functions. A HOC is not part of React's API. It is a pattern built from ordinary composition: the new component renders the original and passes it extra props.
Before hooks arrived, HOCs were a main way to share logic between components. Libraries such as Redux's connect and Relay used them. You will still meet them in older codebases and in some libraries, so you need to read and write them.
A first HOC
This HOC tracks the browser window width and passes it to the wrapped component as a width prop.
import { useEffect, useState } from 'react';
export function withWindowWidth(WrappedComponent) {
function WithWindowWidth(props) {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return <WrappedComponent {...props} width={width} />;
}
return WithWindowWidth;
}You apply it once, outside any component:
import { withWindowWidth } from './withWindowWidth';
function Banner({ title, width }) {
return (
<h1>
{title} ({width}px wide)
</h1>
);
}
export const ResponsiveBanner = withWindowWidth(Banner);Banner stays a plain function of its props. It can be tested by passing width directly, and it does not know where width comes from.
Rules for writing a HOC
Most HOC bugs come from breaking a few rules.
Pass unrelated props through
The wrapper must forward every prop it does not use. Spreading {...props} does this. If you forget, the wrapped component silently loses props the parent provided.
Do not mutate the original component
Do not edit WrappedComponent.prototype or assign to it. Mutation makes the original behave differently everywhere it is used. Always return a new component that wraps the original.
Create the HOC outside render
Call the HOC at module level, not inside another component's body.
function Parent() {
// Wrong: a new component type is created on every render.
const Enhanced = withWindowWidth(Banner);
return <Enhanced title="Hi" />;
}React decides whether to update or remount by comparing component types. A new function each render is a new type, so React unmounts the old subtree and mounts a new one. State inside it is lost on every render of Parent.
Set a display name
Without a name, React DevTools and error messages show Anonymous or the wrapper's internal name. Give the wrapper a name that shows the wrapping.
function getDisplayName(Component) {
return Component.displayName || Component.name || 'Component';
}
export function withWindowWidth(WrappedComponent) {
function WithWindowWidth(props) {
// ...same body as before
return <WrappedComponent {...props} width={0} />;
}
WithWindowWidth.displayName = `withWindowWidth(${getDisplayName(WrappedComponent)})`;
return WithWindowWidth;
}DevTools then shows withWindowWidth(Banner).
Configuring a HOC
A HOC can take extra arguments before the component. This is common for options, such as which key to read from storage.
import { useState } from 'react';
export const withStoredValue = (storageKey) => (WrappedComponent) => {
function WithStoredValue(props) {
const [value, setValue] = useState(() => localStorage.getItem(storageKey));
function save(next) {
localStorage.setItem(storageKey, next);
setValue(next);
}
return <WrappedComponent {...props} storedValue={value} saveValue={save} />;
};
return WithStoredValue;
};
// Usage: two calls, options first, component second.
// const ThemePicker = withStoredValue('theme')(BasePicker);The function returns a function that takes the component. This curried shape makes HOCs easier to compose, because each one has the same signature: component in, component out.
Composing several HOCs
Stacked HOCs nest wrappers. Each layer adds its props and forwards the rest.
const Enhanced = withWindowWidth(withStoredValue('theme')(Banner));Many codebases use a compose helper to flatten the nesting.
const compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x);
const enhance = compose(withWindowWidth, withStoredValue('theme'));
const Enhanced = enhance(Banner);The order matters. compose(a, b)(C) produces a(b(C)), so a is the outermost wrapper.
Common problems
| Problem | Cause | Fix |
|---|---|---|
| Prop is missing in the wrapped component | The wrapper did not spread `props` | Forward `{...props}` |
| State resets on every parent render | HOC called inside a component body | Call the HOC at module level |
| Two HOCs overwrite each other's data | Both inject a prop with the same name | Rename the injected props or namespace them |
| `ref` does not reach the inner element | `ref` is not a normal prop on function components in older React versions | Use `forwardRef` in the wrapper, or pass the ref under another prop name |
| Static methods are gone | The wrapper is a new component without the original's statics | Copy them with a helper such as `hoist-non-react-statics` |
| Stack traces and DevTools are hard to read | Many layers with no display names | Set `displayName` on each wrapper |
React 19 passes ref as an ordinary prop to function components, so the ref problem mostly disappears there. On earlier versions, wrap with forwardRef.
HOCs compared with the alternatives
HOCs, render props and custom hooks all share logic. They differ in where the connection is visible.
| Aspect | HOC | Render prop | Custom hook |
|---|---|---|---|
| Where the data comes from | Hidden: arrives as an injected prop | Visible: function argument in JSX | Visible: a variable in the component body |
| Wrapper layers in the tree | One per HOC | One per render prop component | None |
| Name collisions | Possible | Avoided, you name the argument | Avoided, you name the variable |
| Static typing | Awkward, needs generics | Straightforward | Straightforward |
| Works with class components | Yes | Yes | No |
| Can change what is rendered | Yes, can render nothing or a fallback | Yes | No, hooks return values only |
A HOC can do something hooks cannot: decide whether the wrapped component renders at all. A guard that redirects unauthenticated users is a good example.
import { Navigate } from 'react-router-dom';
export function withAuth(WrappedComponent) {
function WithAuth({ user, ...rest }) {
if (!user) {
return <Navigate to="/login" replace />;
}
return <WrappedComponent user={user} {...rest} />;
}
WithAuth.displayName = `withAuth(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;
return WithAuth;
}This example assumes react-router-dom is installed. Without a router, replace Navigate with a fallback element.
When to choose a HOC
For new function-component code, a custom hook is usually the simplest choice. It adds no layer to the tree and no hidden props. Choose a HOC when:
- The behavior applies to the whole component, such as an auth guard, error boundary wrapper, or analytics tracker.
- You need to wrap class components that cannot call hooks.
- A library you use already exposes its API as a HOC.
- You want to apply the same wrapper to many components in one place, for example in a route table.
Avoid a HOC when the wrapped component needs to control how the shared data is displayed in detail. A render prop or a compound component gives the consumer more control over markup.
Exercise
A teammate writes function Page() { const Safe = withAuth(Dashboard); return <Safe user={user} />; }. The dashboard's form fields reset every time Page re-renders. Why does this happen, and how do you fix it?
Show answer
withAuth(Dashboard) runs on every render of Page and returns a new component function each time. React sees a different component type, so it unmounts the old Dashboard subtree and mounts a fresh one, which discards its state. Fix it by calling the HOC once at module level, for example const SafeDashboard = withAuth(Dashboard);, and rendering <SafeDashboard user={user} /> inside Page.
Exercise
You apply withWindowWidth and a second HOC that also injects a width prop (the width of a container). The wrapped component shows the wrong number. What is happening and what are two ways to fix it?
Show answer
Both HOCs inject a prop named width, so one value overwrites the other depending on wrapper order. You can rename one injected prop, for example windowWidth and containerWidth, or replace one HOC with a custom hook so the component names each value in its own variable.