Context and useContext
Context lets a component read information from the closest matching provider above it without every intermediate component forwarding that value as a prop.
The API is simple. The architectural question is harder:
Is this value really part of the surrounding environment for a subtree, or are we using Context to avoid deciding who owns the state?
Start with propsβ
Props should remain the default way to make dependencies explicit.
If only a small chain needs currency, props may be clearer than introducing a shared environment.
function ProductPage({product, currency}) {
return <ProductCard product={product} currency={currency} />;
}
The problem Context solvesβ
Context becomes useful when the same surrounding information is needed deep in a subtree and intermediate components would otherwise forward it without using it.
Common candidates include theme, locale, session/environment data, feature configuration, form coordination, and feature state/dispatch.
Creating a contextβ
import {createContext} from 'react';
export const ThemeContext = createContext('light');
The context object is a channel, not mutable storage. The default value is used only when no matching provider exists above the consumer.
Providing a value in React 19β
React 19+
function App() {
return (
<ThemeContext value="dark">
<Dashboard />
</ThemeContext>
);
}
Older code commonly uses <ThemeContext.Provider value="dark">. You still need to recognize that syntax for maintenance, but React 19 can render the context object directly as the provider.
Reading contextβ
function Toolbar() {
const theme = useContext(ThemeContext);
return <div className={`toolbar toolbar-${theme}`}>Toolbar</div>;
}
Closest provider winsβ
<ThemeContext value="light">
<Header />
<ThemeContext value="dark">
<AdminPanel />
</ThemeContext>
</ThemeContext>
Header reads light; AdminPanel reads dark.
Providers must already be above consumersβ
This component reads before the provider it returns exists above that read:
function Page() {
const theme = useContext(ThemeContext);
return (
<ThemeContext value="dark">
<Dashboard />
</ThemeContext>
);
}
The provider affects descendants such as Dashboard, not Page's earlier useContext call.
Default valuesβ
const ThemeContext = createContext('light');
With no provider above, the consumer gets 'light'. If a provider explicitly passes undefined, the consumer gets undefined; React does not fall back to the default.
For required application contexts, null plus a validating custom Hook is often safer:
const AuthContext = createContext(null);
export function useAuth() {
const value = useContext(AuthContext);
if (value === null) {
throw new Error('useAuth must be used inside AuthProvider');
}
return value;
}
Context distributes state; it does not create stateβ
export function ThemeProvider({children}) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext value={{theme, setTheme}}>
{children}
</ThemeContext>
);
}
A provider component can combine these responsibilities, but they remain conceptually separate.
Context updates and renderingβ
A consumer that reads a context subscribes to that context value. When the provider's value changes according to Object.is, React can update those consumers.
<ThemeContext value={{theme, setTheme}}>
That object is newly created when the provider renders. This is not automatically a performance problem; measure first. It does mean value identity is relevant when a context has many consumers or changes frequently.
memo does not block context updates because context is another input to the component, separate from props.
Context is tree-scoped, not automatically globalβ
Think tree-scoped dependency, not βglobal variable.β
What belongs in Context?β
Good candidates often share these properties:
- many descendants need the value;
- it represents a surrounding environment or feature state;
- prop forwarding creates real noise;
- consumers should intentionally depend on this provider boundary.
Use props when the relationship is naturally parent β child, only a few consumers need the value, or explicit dependencies improve reusability.
Composition can remove prop drillingβ
Before Context, ask whether composition can move the consumer closer to the owner:
<Layout header={<UserMenu user={user} />} />
Now Layout does not need to receive and forward user merely for UserMenu.
Avoid one giant application Contextβ
<AppContext value={{
user,
products,
cart,
theme,
notifications,
filters,
settings,
}}>
This creates broad coupling and hides ownership.
Split providers by coherent ownership/change boundaries, not by arbitrary file size.
Context is not a server-state cacheβ
Context can transport remote data, but it does not by itself provide cache lifetime, deduplication, staleness, invalidation, retries, background refresh, or mutation coordination.
Server-state tools/framework APIs solve a different lifecycle problem.
Balanced dependency designβ
Debugging Contextβ
If a consumer gets the wrong value, check whether the provider is actually above it, whether a nearer provider overrides it, whether the provider supplies value, whether a default masks a missing provider, and whether provider/consumer import the exact same context object.
Production pattern: provider + custom Hookβ
const CartContext = createContext(null);
export function CartProvider({children}) {
const [items, setItems] = useState([]);
return (
<CartContext value={{items, setItems}}>
{children}
</CartContext>
);
}
export function useCart() {
const context = useContext(CartContext);
if (context === null) {
throw new Error('useCart must be used inside CartProvider');
}
return context;
}
Benefits include validated provider requirements, fewer direct Context imports, and a stable feature API that can evolve internally.
Context decisionβ
Exerciseβ
Build a theme system with nested providers, a useTheme Hook, a toolbar that reads the nearest theme, and a toggle that updates only one provider subtree. Explain which component owns the state and what Context contributes.
Interview questionsβ
Junior: What problem does Context solve?
Mid-level: Why is Context not automatically a replacement for props or a state-management library?
Senior: How would you choose provider boundaries in a large application, and what rendering/coupling trade-offs would you inspect before optimizing Context?
Summaryβ
Referencesβ
- https://react.dev/learn/passing-data-deeply-with-context
- https://react.dev/reference/react/createContext
- https://react.dev/reference/react/useContext
Nextβ
Continue with Context Architecture and Performance.