How to Manage State in React with Context API
Ad
What is the Context API?
The Context API lets you share state across many components without passing props down every level (a problem called "prop drilling"). It's built into React — no library needed.
Step 1: Create the Context
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext();
Step 2: Create a Provider
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
const toggle = () => setTheme(t => (t === "light" ? "dark" : "light"));
return (
<ThemeContext.Provider value={{ theme, toggle }}>
{children}
</ThemeContext.Provider>
);
}
Step 3: Wrap Your App
<ThemeProvider>
<App />
</ThemeProvider>
Step 4: Consume Anywhere
function Header() {
const { theme, toggle } = useContext(ThemeContext);
return <button onClick={toggle}>Theme: {theme}</button>;
}
When to Use Context vs Redux/Zustand
- Context — theme, auth user, language. Low-frequency updates.
- Zustand / Redux — large apps, high-frequency updates, complex state logic.
Performance Warning
Every component consuming a context re-renders when its value changes. Split contexts (one for theme, one for user) to limit re-renders.
FAQs
Is Context a replacement for Redux?
For simple global state, yes. For complex apps with middleware and devtools, dedicated libraries are still better.
Why is my whole app re-rendering?
You're probably creating a new value object every render. Memoise it with useMemo. More in our React guides.
