useContext
Subject: React
๐ What is useContext
?
useContext
is a React Hook that allows components to access global/shared data without prop drilling.
Think of it like a global variable โ any component can read from it, no matter how deep it is in the component tree.
๐ Why Use useContext
Without Context | With Context |
---|---|
Pass data parent โ child โ subchild | Access data directly in any component |
Complex and repetitive prop chains | Cleaner and more scalable |
Tedious to update/apply globally | Simple global data flow |
๐ ๏ธ Real Use Cases
- Authenticated user info
- Theme (light/dark)
- Language (i18n)
- App-wide preferences/settings
- Combine with
useReducer
for global state
๐ฆ Basic Setup of Context
โ Example: Share User Data Across Components
UserContext.js
App.js
Dashboard.js
๐ง Logic Explained
Step | Description |
---|---|
createContext() | Creates a Context object |
Provider | Makes the value available to children |
useContext(Context) | Hook to read the value in any nested component |
Value Flow | Parent โ Provider โ Any child component |
โ Dynamic Updates with Context
Example:
Access + update from anywhere:
โ ๏ธ When NOT to Use Alone
- For complex global state, combine with
useReducer
- Frequent context updates? โ Use React.memo or split into smaller contexts
๐ Summary Table
Feature | Description |
---|---|
createContext() | Creates context container |
Provider | Wraps components and shares a value |
useContext() | Reads the shared value inside any component |
Avoids | Prop drilling |
Best For | Theme, auth, user info, i18n, shared app settings |
๐งช Real-Life Analogy
Context is like cloud storage:
- Upload data once using a
Provider
- Any connected component ("device") can download it using
useContext
Advertisement Slot 1
Advertisement Slot 2