Context makes a value available to components below a provider without manually passing it through every intermediate component.
1 Prop Drilling
App
-> Layout
-> Sidebar
-> UserMenu
-> UserProfile
If every component passes the user only because UserProfile needs it, the application has unnecessary prop drilling.
2 Context Flow
flowchart TD
A[Provider] --> B[Component A]
A --> C[Component B]
A --> D[Deep Component]
D --> E[useContext]
3 Create and Provide Context
const UserContext = createContext(null);
function App() {
const user = { name: "Rahul", role: "Admin" };
return (
<UserContext.Provider value={user}>
<Dashboard />
</UserContext.Provider>
);
}
4 Consume Context
function UserProfile() {
const user = useContext(UserContext);
return (
<div>
<h2>{user.name}</h2>
<p>{user.role}</p>
</div>
);
}
5 Authentication Example
const AuthContext = createContext(null);
function AuthProvider({ children }) {
const [user, setUser] = useState(null);
function login(userData) { setUser(userData); }
function logout() { setUser(null); }
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
}
6 Custom Context Hook
function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used inside AuthProvider");
}
return context;
}
7 Context and Re-rendering
When a provider value changes, components consuming that context can render again. Frequently changing values should therefore be designed carefully.
8 Context vs Props
| Props | Context |
|---|---|
| Explicit parent-to-child communication | Shared descendant value |
| Clear local data flow | Reduces repeated prop passing |
| Good for direct relationships | Good for cross-cutting values |
9 Context Is Not Automatically a Complete State Library
Context shares values. It does not automatically provide every feature required by a large state-management architecture.
10 Common Mistakes
- Putting every state value into Context.
- Creating one huge frequently changing context.
- Using consumers outside the provider.
- Ignoring context-driven re-renders.
11 Interview Questions
- What is Context?
- What is prop drilling?
- How do you create and consume Context?
- What does useContext do?
- When should Context be used?
- Does Context replace every state-management library?
12 Key Takeaways
- Context shares values with descendants.
- It can reduce prop drilling.
- useContext reads the nearest provider value.
- Use Context for genuinely shared data.
Conclusion
Context is useful for cross-cutting values such as theme, locale, and authentication-related UI state. Use it deliberately rather than making every state value global.