React useContext Hook
🌍 React useContext Hook
The useContext Hook allows you to use global state across your React app without passing props manually through multiple components (called prop drilling).
It is used with the React Context API.
❌ Problem Without Context
If a value needs to be passed to deep child components:
You would need to pass props down through each level, even if the components don’t use the value.
This is called prop drilling and is hard to maintain.
✅ Solution: useContext + Context API
Context lets you:
✔ Share data globally
✔ Avoid prop drilling
✔ Make cleaner component structure
🛠 Step 1: Create Context
🛠 Step 2: Wrap Components with Provider
📌 value holds the data shared globally.
🛠 Step 3: Consume Context with useContext
🧪 Example Output:
🔁 Updating Context Value
You can also update context using state inside the provider:
Child component:
🎯 When to Use useContext
Use it when:
✔ Data must shared across multiple components
✔ Avoid deep prop passing
✔ Global settings like:
-
Theme (dark/light mode)
-
Authentication (logged in user)
-
Language settings
-
Shopping cart data
⚠️ When NOT to Use Context
❌ For high-frequency updates (like animation or fast-changing data) — performance may drop.
Better alternatives: Redux, Zustand, Recoil.
🧠 Summary
| Feature | Yes/No |
|---|---|
| Avoids prop drilling | ✅ |
| Global state sharing | ✅ |
| Easy with functional components | ✅ |
| Replacement for Redux? | ❌ Not always |
