React Higher-Order Components (HOC)
React Higher-Order Components (HOC)
A Higher-Order Component (HOC) is a function that takes a component and returns a new enhanced component.
It allows you to reuse component logic, similar to higher-order functions in JavaScript.
✅ Definition
HOCs do not modify the original component.
They wrap the component and return a new one with added features.
🔥 Why Use HOCs?
HOCs are useful for:
| Use Case | Examples |
|---|---|
| Reusability | Authentication handling, API fetching |
| Logic sharing | Data fetching, validation |
| Conditional rendering | Loading spinners, permissions |
| State enhancement | Provide additional props |
🧠 Basic HOC Example
Usage:
🚀 Example: HOC for Loading State
Usage:
Render:
🎯 Passing Props in HOCs
Always pass existing props using:
Otherwise, original props will be lost.
⚠️ Best Practices
✔ Always copy props
✔ Name wrapped components for debugging
✔ Prefer Hooks instead of HOCs for modern React
❌ When NOT to Use HOCs
Since React v16+ and hooks, many old HOC use cases can be replaced with:
useEffectuseContextCustom hooks
Example alternative:
📌 Summary
| Feature | Value |
|---|---|
| What is it? | Function that adds extra behavior to a component |
| Returns | A new component |
| Common Use | Logic reuse, conditional UI, permissions |
| Modern Alternative | Custom Hooks |
