Sub topic 4
Higher-order components
This chapter assumes you know function components, props, JSX, useState, and how to pass functions as props. You should also be comfortable with ES modules and destructuring.
What a higher-order component is
A higher-order component (HOC) is a function that takes a component and returns a new component. The new component wraps the original and adds behavior, usually by supplying extra props.
const EnhancedComponent = withSomething(BaseComponent);The name comes from higher-order functions, which take or return other functions. By convention, HOC names start with with.
A worked example
Suppose several components need to know whether the user is online. You could repeat the same state and event listeners in each one. A HOC puts that logic in one place.
import { useEffect, useState } from 'react';
export function withOnlineStatus(WrappedComponent) {
function WithOnlineStatus(props) {
const [online, setOnline] = useState(navigator.onLine);
useEffect(() => {
const update = () => setOnline(navigator.onLine);
window.addEventListener('online', update);
window.addEventListener('offline', update);
return () => {
window.removeEventListener('online', update);
window.removeEventListener('offline', update);
};
}, []);
return <WrappedComponent {...props} online={online} />;
}
const name = WrappedComponent.displayName || WrappedComponent.name || 'Component';
WithOnlineStatus.displayName = `withOnlineStatus(${name})`;
return WithOnlineStatus;
}
function StatusBadge({ online, label }) {
return <span>{label}: {online ? 'Online' : 'Offline'}</span>;
}
export const OnlineStatusBadge = withOnlineStatus(StatusBadge);Use it like any other component: <OnlineStatusBadge label="Network" />. The label prop passes through the wrapper because of {...props}, and online is added by the HOC.
Common errors
- Creating the HOC inside render. Calling
withOnlineStatus(StatusBadge)inside a component makes a new component type on every render. React then unmounts and remounts the subtree, which loses state. Call HOCs at module level. - Not forwarding props. If you forget
{...props}, the wrapped component silently loses the props its parent passed. - Prop name collisions. If the HOC injects
onlineand the parent also passesonline, one overwrites the other. Pick specific names or let callers configure them. - Missing display names. Without
displayName, React DevTools shows many components calledWithOnlineStatus. Setting it, as above, makes the tree readable. - Lost refs.
refis not an ordinary prop in older React versions, so a HOC does not forward it to the wrapped component unless you useforwardRef.
When to use HOCs
HOCs work well for cross-cutting concerns that wrap a whole component, such as authentication guards, error boundaries, or analytics. They also appear in older libraries, so you will meet them in existing code.
For most new logic sharing, a custom hook is simpler. It needs no wrapper component, adds no extra layer to the tree, and makes data flow visible in the component that uses it. Hooks also avoid the prop collision problem because you choose the variable names.
Exercise
Why does calling const Enhanced = withOnlineStatus(StatusBadge) inside a component's render function cause problems?
Show answer
Each render creates a new component type. React treats it as a different component from the previous render, so it unmounts the old subtree and mounts a new one, which resets state and can hurt performance. Call the HOC once at module level instead.
Exercise
Rewrite the online-status logic as a custom hook so that StatusBadge can get online without a wrapper. What is the main trade-off versus the HOC?
Show answer
Write function useOnlineStatus() { const [online, setOnline] = useState(navigator.onLine); useEffect(() => { const update = () => setOnline(navigator.onLine); window.addEventListener('online', update); window.addEventListener('offline', update); return () => { window.removeEventListener('online', update); window.removeEventListener('offline', update); }; }, []); return online; }, then call const online = useOnlineStatus(); inside StatusBadge. The hook makes data flow explicit and avoids wrapper layers and prop collisions. The cost is that each component must call the hook itself, whereas a HOC can apply behavior without editing the base component.