What is a higher-order component (HOC)? Give an example, and explain why custom hooks have replaced most HOCs.
Show the explanation
Model answer. A higher-order component is a function that takes a component and returns a new component with extra behaviour or props, the component version of a higher-order function.
function withAuth(Component) {
return function Protected(props) {
const user = useCurrentUser();
if (!user) return <Navigate to="/login" />;
return <Component {...props} user={user} />;
};
}
const ProtectedSettings = withAuth(Settings);Historically, HOCs (and render props) were the main way to share logic between class components: Redux's connect, React Router's old withRouter.
Drawbacks:
- "Wrapper hell": many nested layers in DevTools.
- Prop name collisions when two HOCs inject the same prop.
- Indirection: it is unclear where a prop came from.
- Static typing is awkward.
A custom hook shares the same logic more directly: const user = useCurrentUser();. No extra component, no hidden props, and it composes easily.
HOCs are still reasonable for cross-cutting concerns that wrap rendering, such as an error boundary or an access-control wrapper around a whole route.
Original UniCircle question. Last reviewed 22 Oct 2026.
