What are the downsides of higher order components that led many developers to prefer custom hooks instead?
Short answer
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.
Advertisement
AModel answer
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.
Likely 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?
Related topics