REACT & NEXT.JS / 4. CONTEXT & STATE MANAGEMENT
Context API & State Management
Sharing state without prop drilling
EXPLANATION
Prop drilling: passing props through many layers of components just to reach a deeply nested child. Context solves this.
Context: a way to share values between components without passing props at every level.
Three parts:
1. createContext() → creates the context object
2. <Context.Provider value={...}> → wraps components that need access
3. useContext(Context) → reads the value inside any descendant
When to use Context:
• Theme (dark/light mode)
• Authentication state (current user)
• Language/locale
• Global UI state (sidebar open/closed)
When NOT to use Context:
• Frequently changing state (causes all consumers to re-render)
• Server state (use React Query / SWR instead)
• Complex state logic (use Zustand or Redux)
Custom hook pattern: wrap useContext in a custom hook for better DX and error handling.
Zustand: lightweight state management library. Much simpler than Redux, better than Context for frequently updated state.DIAGRAM
Without Context (prop drilling):
App(user) → Layout(user) → Sidebar(user) → Avatar(user)
user passed through every layer even if Layout/Sidebar don't need it
With Context:
<UserContext.Provider value={user}>
<Layout> ← doesn't receive user
<Sidebar> ← doesn't receive user
<Avatar /> ← useContext(UserContext) → gets user directly
</Sidebar>
</Layout>
</UserContext.Provider>
Zustand store:
create(set => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 }))
}))
→ use in any component, no Provider neededCODE