React Context API (Managing Global State)
Introduction
As your React application grows, passing data from parent to child components using props can become complex. When many components need the same data, this process is called prop drilling, and it can make the code harder to manage.
To solve this problem, React provides the Context API. It allows you to share data across multiple components without passing props manually at every level.
What Is the Context API?
The Context API is a built-in feature in React that helps manage global data. Global data can include themes, user authentication details, language preferences, or application settings.
Instead of sending props through many layers of components, Context allows any component inside it to access shared data directly.
Creating a Context
To use Context, first create it using createContext.
import { createContext } from "react";
const ThemeContext = createContext();
This creates a Context object that will hold shared data.
Providing Context to Components
Next, wrap the components that need access to the data with a Provider.
import { useState } from "react";
function App() {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Main />
</ThemeContext.Provider>
);
}
The value prop contains the data you want to share.
Consuming Context Data
Components can access context data using the useContext hook.
import { useContext } from "react";
function Header() {
const { theme } = useContext(ThemeContext);
return <h2>Current Theme: {theme}</h2>;
}
Now Header can use the theme value without receiving it as a prop.
Updating Context Data
Since we passed setTheme in the Provider value, components can update the global state.
function ThemeButton() {
const { setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme("dark")}>
Switch to Dark Theme
</button>
);
}
Updating the context triggers re-renders in components that use it.
When to Use Context
Context is useful when:
Many components need the same data
Props are passed deeply through the component tree
You want centralized data control
It is not ideal for very frequent updates or complex state logic — for those, advanced state management libraries may be better.
Common Mistakes to Avoid
Using Context for a small, local state
Overusing Context instead of component composition
Forgetting to wrap components with the Provider
Summary
In this chapter, you learned how the Context API helps share global data across components without prop drilling. You created a context, provided values using a Provider, consumed them with useContext, and updated shared state. Context makes large React applications cleaner and easier to maintain.