A Higher-Order Component (HOC) is a function that takes a component and returns a new component with extra features.
1. Analogy ☕
Think of a coffee cup (your component).
A HOC is like a sleeve you put around the cup: it doesn’t change the coffee, but it adds insulation (extra functionality).
2. Why Use HOCs?
- Reusability → extract and share common logic.
- Separation of concerns → UI components stay simple, HOCs handle cross-cutting logic.
- Composition → wrap components with multiple behaviors.
3. Example
// HOC that adds a loading spinner
function withLoading<P>(Component: React.ComponentType<P>) {
return function WrappedComponent(props: P & { loading: boolean }) {
if (props.loading) {
return <div>Loading...</div>
}
return <Component {...props} />
}
}
// Usage
function UserProfile({ name }: { name: string }) {
return <h2>{name}</h2>
}
const UserProfileWithLoading = withLoading(UserProfile)
// Render
<UserProfileWithLoading loading={true} name="Alice" />
👉 If loading
is true → show spinner. Otherwise, show UserProfile
.
4. Common Use Cases
- Auth wrapper → redirect if not logged in.
- Analytics wrapper → log component views.
- Data fetching → provide fetched data as props.
- UI wrappers → error boundaries, animations, styles.
5. Downsides
- Can cause wrapper hell (too many nested HOCs).
- Makes React DevTools component tree messy.
- Harder to type with TypeScript.
- Modern React often prefers Hooks instead.
6. HOCs vs Hooks
Feature | HOCs ✅ | Hooks ✅ |
---|---|---|
Share logic across comps | ✔️ Yes | ✔️ Yes |
Simple composition | ❌ Can get messy | ✔️ Very clean |
Works in class components | ✔️ Yes | ❌ No (hooks = function comps only) |
DevTools readability | ❌ No | ✔️ Clear |
Modern React preference | ⚠️ Legacy pattern | ✔️ Recommended |
7. Quick Mental Model 🧠
- HOC = function wrapper → adds behavior → returns new component.
- Use it for auth, logging, theming, analytics wrappers.
- Prefer hooks for most new code.
⚡ That’s it! HOCs are still useful in some cases, but hooks are the modern go-to for sharing React logic.
Originally published on: Bitlyst
Top comments (2)
I totally agree with this view
I also used HOCs to share logic between components in the beginning, especially for loading or authentication. But when the project got bigger, combining HOCs sometimes caused complexity and wrapper hell.
Now I try to use Hooks more and I feel that both the code readability is better and TypeScript is easier to work with.
Do you still see a place for HOCs in big projects or are Hooks almost everywhere?
I'm using Hooks most of the times, but sometimes it's a good feature.
Thanks for your asking.