4. Understanding useContext (Simple Global State)
Why useContext Exists
Passing props through many layers is called prop drilling.
Example:
App → Layout → Sidebar → Profile → Avatar
Only Avatar needs the data 😩
What Is Context?
Context lets you:
- Store data once
- Access it anywhere below
Think:
“Make this data global.”
Simple Context Example
const UserContext = React.createContext();
function App() {
const [user, setUser] = useState(null);
return (
<UserContext.Provider value={{ user, setUser }}>
<Dashboard />
</UserContext.Provider>
);
}
Using it:
const { user } = useContext(UserContext);
When to Use Context
Good for:
- Logged-in user
- Theme
- Language
- App-wide settings
Bad for:
- Frequently changing data
- Very complex logic
Common Beginner Mistake
Using Context for everything.
Context is not Redux.
Key Takeaway
Context is great for simple global data, not complex app logic.
Top comments (0)