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 CaseExamples
ReusabilityAuthentication handling, API fetching
Logic sharingData fetching, validation
Conditional renderingLoading spinners, permissions
State enhancementProvide 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:

  • useEffect

  • useContext

  • Custom hooks

Example alternative:


📌 Summary

FeatureValue
What is it?Function that adds extra behavior to a component
ReturnsA new component
Common UseLogic reuse, conditional UI, permissions
Modern AlternativeCustom Hooks

You may also like...