React · Lesson 7 of 15 · 4 min
Context API for Global State
This is how you explain state management trade-offs beyond useState.
After this lesson, you'll know when to reach for Context, when to use something else, and how to explain the performance implications to an interviewer. Context is a dependency injection mechanism, not a full-fledged state management library. Knowing the difference is critical.
Solve Prop Drilling, Not Global State
The main problem Context solves is "prop drilling." This is when you pass props through several layers of components that don't need them, just to get data to a deeply nested child.
Prop drilling makes components hard to refactor and reuse. Every intermediate component becomes coupled to the props it's just passing along.
Context lets you bypass this. A Provider makes a value available, and any descendant component can consume it directly.
Think of Context as a teleportation device for a specific piece of data, making it available anywhere inside a boundary without having to pass it through every intermediate stop.
How to Build a Reusable Context Provider
The standard pattern isn't just createContext and useContext. A robust implementation combines the context, provider component, and a custom consumer hook into a single file. This gives you a clean, safe API.
createContext: Define the "shape" of your context data and create the context object. Initialize it withundefined.- Provider Component: A wrapper component that holds the state (
useStateoruseReducer) and passes it into theProvider'svalueprop. - Custom Hook: A
useMyContexthook that callsuseContextand adds a runtime check. IfuseContextreturnsundefined, it means the hook is being used outside the provider. This fails fast and tells you exactly where the bug is.
Here is a complete, production-ready example for a theme context.
import { createContext, useContext, useState, useMemo, ReactNode } from 'react';
// 1. Define the context's value shape
type Theme = 'light' | 'dark';
interface ThemeContextType {
theme: Theme;
toggleTheme: () => void;
}
// 2. Create the context, initially undefined
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
// 3. Create the Provider component
interface ThemeProviderProps {
children: ReactNode;
}
export const ThemeProvider = ({ children }: ThemeProviderProps) => {
const [theme, setTheme] = useState<Theme>('light');
const toggleTheme = () => {
setTheme(prevTheme => (prevTheme === 'light' ? 'dark' : 'light'));
};
// IMPORTANT: Memoize the value to prevent unnecessary re-renders
const value = useMemo(() => ({ theme, toggleTheme }), [theme]);
return (
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
);
};
// 4. Create the custom consumer hook
export const useTheme = () => {
const context = useContext(ThemeContext);
if (context === undefined) {
// This error is a huge help during development.
throw new Error('useTheme must be used within a ThemeProvider');
}
return context;
};
To use it, wrap a part of your component tree with <ThemeProvider> and call useTheme() in any child component that needs the theme data.
The Performance Trap: Context Re-renders Everything
When the value prop of a Provider changes, React re-renders all components that consume that context, regardless of whether they use the specific piece of data that changed.
The trap: Creating a new object for the value prop on every render.
// BAD: A new object is created on every render of MyProvider
<MyContext.Provider value={{ theme, toggleTheme }}>
{children}
</MyContext.Provider>
This causes every consumer to re-render, even if theme and toggleTheme haven't changed. The object reference is new, so React sees it as a change.
This is why useMemo (for objects) and useCallback (for functions) are not optional optimizations for Context—they are essential for correct behavior. You must ensure the value object has a stable identity.
Because of this re-render behavior, Context is best for state that changes infrequently, like a user's theme, authentication status, or language preference. For high-frequency updates, like form input state, it's the wrong tool.
Answering "When Would You Use Context vs. Redux?"
This question tests your understanding of trade-offs. There is no single right answer, but there is a right way to frame the comparison. Avoid saying one is "better." Instead, describe what each is designed for.
In an interview, frame your answer like this: "I choose the tool based on the type of state. For low-frequency global data like user authentication or theme, React Context is perfect. It's built-in and simple. For complex, high-frequency application state that many components interact with, like a normalized cache of server data, I'd use a dedicated library like Redux or Zustand. They offer better performance through selective subscriptions and provide powerful dev tools for debugging complex state changes."
Here's a breakdown:
| Concern | React Context | Redux / Zustand | | :--- | :--- | :--- | | Use Case | Low-frequency "global" data. (Theme, auth, locale). | Complex, high-frequency app state. (Server cache, form state). | | Re-renders | Re-renders all consumers on any value change. | Optimized; components subscribe to specific state slices and only re-render when those slices change. | | Boilerplate | Low. Built into React. | Higher (Redux) to very low (Zustand). | | Dev Tools | None. Debugging is done via React DevTools. | Excellent. Time-travel debugging, action inspection. | | Middleware | No built-in concept. You can build it, but it's not standard. | Core feature for handling side effects (e.g., API calls). |
Context is a dependency injection tool. Redux is a predictable state container. Use them for what they were built for.
Try it
Take a component tree in one of your projects that passes a prop down three or more levels. Refactor it to use a Context Provider. Create a custom hook to consume the context and ensure you memoize the provider's value prop. The whole exercise should take about 20 minutes.
Next: We'll look at how to directly interact with the browser's DOM using useRef and forwardRef in the lesson on "Working with Refs & the DOM".
Lock it in — apply this lesson under interview conditions.