State Management – Context API
Introduction
State management is a core concept in React applications. As applications grow, managing and sharing data between multiple components becomes challenging. React’s Context API provides a built-in solution to manage global state without passing props through every level of the component tree.
Context API is ideal for managing data such as user authentication, themes, language preferences, and application settings.
What is State Management?
State management refers to how data is:
- Stored
- Updated
- Shared across components
In small applications, local component state is enough. In larger applications, state often needs to be shared across many unrelated components, which is where Context API becomes useful.
What is Context API?
The Context API is a React feature that allows you to:
- Create a global state
- Provide it to the component tree
- Consume it anywhere without prop drilling
It was introduced to solve the problem of passing data manually through multiple layers of components.
What is Prop Drilling?
Prop drilling occurs when data is passed from a parent component to deeply nested child components through intermediate components that do not need the data.
This leads to:
- Messy code
- Harder maintenance
- Reduced readability
Context API eliminates this issue.
When Should You Use Context API?
Use Context API when:
- Data needs to be accessed by many components
- Props are being passed deeply
- Global state is simple and stable
Examples:
- Logged-in user data
- Theme (dark/light)
- Language selection
- App-wide settings
When Not to Use Context API?
Avoid Context API when:
- State is frequently changing at high speed
- State is very complex
- Performance is critical at scale
In such cases, tools like Redux or Zustand are better options.
Core Components of Context API
- createContext
- Provider
- Consumer (or useContext hook)
Step-by-Step Example Using Context API
Step 1: Create a Context
import { createContext } from "react";
const UserContext = createContext(null);
export default UserContext;
Step 2: Create a Context Provider
import { useState } from "react";
import UserContext from "./UserContext";
function UserProvider({ children }) {
const [user, setUser] = useState(null);
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
}
export default UserProvider;
Explanation:
- Provider holds shared state
- value defines what data is exposed globally
Step 3: Wrap the App with Provider
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import UserProvider from "./UserProvider";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<UserProvider>
<App />
</UserProvider>
);
Step 4: Consume Context Using useContext
import { useContext } from "react";
import UserContext from "./UserContext";
function Profile() {
const { user, setUser } = useContext(UserContext);
return (
<div>
<p>User: {user}</p>
<button onClick={() => setUser("John")}>Login</button>
</div>
);
}
export default Profile;
Explanation:
- useContext reads data directly from Context
- No props are required
How Context API Works Internally
- Provider stores global state
- React tracks which components consume the context
- When context value changes, only subscribed components re-render
Context API with Multiple States
You can store multiple values in one context.
value={{ user, theme, language }}
For large apps, it is recommended to create multiple contexts instead of one large context.
Performance Considerations
- Context updates re-render all consumers
- Avoid storing rapidly changing data
- Split contexts by responsibility
- Memoize values if needed
Context API vs Redux
| Feature | Context API | Redux |
|---|---|---|
| Built-in | Yes | No |
| Boilerplate | Low | High |
| Best for | Small to medium apps | Large complex apps |
| DevTools | Limited | Advanced |
| Async handling | Manual | Middleware |
Common Mistakes with Context API
- Using context for every state
- Not separating contexts
- Forgetting to wrap Provider
- Overusing global state
- Ignoring performance impact
Interview Questions and Answers – Context API
1. What is Context API in React?
Context API is a built-in feature for managing and sharing global state across components.
2. Why is Context API used?
It avoids prop drilling and simplifies state sharing.
3. What are the main parts of Context API?
createContext, Provider, and Consumer or useContext.
4. What hook is used to consume context?
useContext.
5. Is Context API a replacement for Redux?
No, it is suitable for simpler global state needs.
6. Does Context API cause re-renders?
Yes, all consuming components re-render when context value changes.
7. Can we use multiple contexts?
Yes, it is recommended for better separation of concerns.
8. Where should Provider be placed?
At the top level of the component tree.
9. Can Context API handle async data?
Yes, but async logic must be handled manually.
10. Is Context API part of React core?
Yes, it is built into React.
Your Feedback
Help us improve by sharing your thoughts
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.
