React Context API
π What is Context API?
The Context API is a built-in React feature that allows you to share data globally across components without passing props manually at every level.
π It solves the problem of prop drilling.
π₯ What is Prop Drilling?
Prop drilling happens when you pass data through multiple intermediate components:
<App user={user}>
<Parent user={user}>
<Child user={user}>
<DeepChild user={user} />
</Child>
</Parent>
</App>
β Problems:
Boilerplate code
Hard to maintain
Unnecessary dependencies
β Context API Solution
Instead of passing props manually, Context lets you:
π βBroadcast data to any component that needs itβ
βοΈ How Context API Works (Core Concepts)
There are 3 main parts:
1. createContext()
Creates a context object
const MyContext = React.createContext();
2. Provider (Source of Data)
Wrap components with a provider
<MyContext.Provider value={data}>
<App />
</MyContext.Provider>
3. Consumer (Access Data)
Use useContext hook
const value = useContext(MyContext);
β Step-by-Step Practical Example
π― Use Case: User Authentication
1. Create Context
import { createContext } from "react";
export const AuthContext = createContext();
2. Provide Data (Top Level)
import React, { useState } from "react";
import { AuthContext } from "./AuthContext";
function App() {
const [user, setUser] = useState("Pushpesh");
return (
<AuthContext.Provider value={{ user, setUser }}>
<Dashboard />
</AuthContext.Provider>
);
}
3. Consume Data Anywhere
import React, { useContext } from "react";
import { AuthContext } from "./AuthContext";
function Dashboard() {
const { user, setUser } = useContext(AuthContext);
return (
<>
<h1>Welcome {user}</h1>
<button onClick={() => setUser("Admin")}>
Switch User
</button>
</>
);
}
β What Just Happened?
Appholds global stateDashboardaccesses it directlyNo props needed β
π§© Best Practices (VERY IMPORTANT)
β 1. Keep Context Focused
β Bad (everything in one context)
<AppContext value={{ user, theme, cart, settings }}>
β Good (split contexts)
<AuthContext />
<ThemeContext />
<CartContext />
β 2. Wrap Logic in Custom Hooks
π Cleaner and reusable
export const useAuth = () => {
return useContext(AuthContext);
};
Usage:
const { user } = useAuth();
β 3. Keep Heavy Logic Outside Context
Context should:
β NOT contain complex reducers/business logic
β ONLY share state
β 4. Avoid Frequent Updates
π Context re-renders all consumers
So avoid putting:
- rapidly changing data (e.g., typing input)
β οΈ Limitations of Context API
This is where many developers misuse it.
β 1. Performance Issues
Whenever context value changes:
π ALL components using it re-render
Even if they donβt need the update.
β 2. Not Ideal for Complex State
If your app has:
Multiple state slices
Nested logic
Async operations
Context becomes messy
β 3. Hard to Scale
Large apps become:
Hard to debug
Hard to track data flow
π When NOT to Use Context β Use Redux Toolkit
π« Avoid Context if:
β 1. Large Global State
Example:
E-commerce app
Dashboard with many modules
β 2. Complex State Logic
Example:
Multiple reducers
Derived state
Async API calls
β 3. Frequent Updates
Example:
Real-time data
Animations
Typing input shared globally
β 4. Need Dev Tools & Debugging
Context:
- No built-in debugging
Redux Toolkit:
- DevTools support β
β When to Use Redux Toolkit Instead
Redux Toolkit is better when:
β 1. App is Large & Scalable
- Many features connected together
β 2. Complex Business Logic
Example:
Cart system
Order flow
β 3. Async Operations
Redux Toolkit has:
createAsyncThunk
β 4. Predictable State Management
Redux ensures:
Centralized store
Clear state transitions
βοΈ Context API vs Redux Toolkit
| Feature | Context API | Redux Toolkit |
|---|---|---|
| Setup | Simple | Moderate |
| Best For | Small/global data | Large apps |
| Performance | Can re-render often | Optimized |
| Debugging | Basic | DevTools β |
| Async handling | Manual | Built-in β |
| Scalability | Limited | High |
π§ Real Developer Decision Guide
β Use Context API When:
Auth user data
Theme (dark/light)
Language settings
App-level config
β Use Redux Toolkit When:
Complex workflows
Many interconnected states
Global state with logic
API-heavy apps
π§ Final Mental Model
Think like this:
π‘ Context API = WiFi Router
Broadcast data
Simple usage
No control over who uses what
π¦ Redux Toolkit = Bank System
Structured
Secure
Controlled updates
Full transaction history
π Final Takeaway
Use Context API for simple shared state, but switch to Redux Toolkit when your app grows in complexity, scale, and logic.