React Higher-Order Components (HOC)
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.
How did you like this post?
👍0
❤️0
🔥0
🤔0
😮0