Context for Shared State in React
Learn how React context providers pass typed values to consumers, when context helps avoid prop drilling, and when local state or a store fits better.
React context passes a provider value to descendants without forwarding props through every component. This guide shows a typed theme context, a guarded hook for missing providers, and how to choose between context, local state, props, or a store. Use the examples to keep shared state scoped to the components that need it, while leaving authorization and secrets on the server.
Context for Shared State in React
Introduction
React context lets a parent provide a value deep in a component tree without intermediate components forwarding it. A theme shared by a toolbar and preview is a common example.
Context carries a value; state still lives in a component. Use local state for one owner. Consider context when many descendants need a changing value and passing props becomes awkward. It does not replace props or a state store by default.
We will build a typed theme provider, read it with a guarded hook, and compare context with local state and props.
Provider, value, and consumer
A provider owns the changing state and passes a typed value to descendants. This example uses undefined as the default so a custom hook can catch a missing provider instead of quietly returning a fake theme:
import { createContext, useContext, useState, type ReactNode } from "react";
type Theme = "light" | "dark";
interface ThemeContextValue {
theme: Theme;
toggleTheme: () => void;
}
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);
function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<Theme>("light");
const toggleTheme = () => {
setTheme((current) => (current === "light" ? "dark" : "light"));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
function useTheme(): ThemeContextValue {
const value = useContext(ThemeContext);
if (!value) throw new Error("useTheme must be used inside ThemeProvider");
return value;
}
function ThemeToggle() {
const { theme, toggleTheme } = useTheme();
return <button onClick={toggleTheme}>Theme: {theme}</button>;
}
function App() {
return (
<ThemeProvider>
<ThemeToggle />
</ThemeProvider>
);
}
The provider owns the state, and the hook guards against rendering outside it. ThemeToggle reads the current value and calls the update callback.
Follow the provider tree
flowchart TD
A[ThemeProvider owns theme] --> B[Header]
A --> C[Main]
B --> D[ThemeToggle consumer]
C --> E[Preview consumer]
When to Use / When NOT to Use
Use context for subtree values such as theme or locale when prop passing becomes repetitive. Keep one-control values local; for two nearby components, lift state to their parent and pass props. Avoid context when it only hides a simple parent-child relationship.
For a value used by one control, keep it local:
function SearchBox() {
const [query, setQuery] = useState("");
return (
<input
value={query}
onChange={(event) => setQuery(event.currentTarget.value)}
/>
);
}
The theme above is different: both the header and preview read it, so their nearest shared owner can provide it through context. Context is for sharing a value down that subtree, not a place to put every piece of state.
Trade-Off Table
| Approach | Use it when | Trade-off |
|---|---|---|
| Local state and props | One owner or a few nearby components use the value | Values must be passed through component boundaries |
| Context | Many descendants need the same subtree value | Consumers update when the provided value changes |
| State store | State has complex transitions or many distant subscribers | Adds a library or more setup and conventions |
Start with state and props; add context when prop passing gets repetitive. A store may fit better when many distant subscribers or complex updates need selectors and tooling.
Production Failure Scenarios
A consumer rendered outside ThemeProvider may crash when it reads the value. A default such as "light" can hide the missing provider; the guarded hook fails clearly. Wrap the consumer in the provider or choose a fallback only when it is valid.
A provider that combines unrelated, frequently changing values can rerender consumers that only need a stable value. Split contexts by ownership, and only memoize provider values after profiling shows avoidable work.
Security and Compliance Notes
Context is not access control. Enforce permissions on the server and keep secrets out of browser state.
Common Pitfalls and Anti-Patterns
Avoid creating context inside a component, using a fake default, or combining unrelated values in one provider. Split contexts when ownership differs.
Quick Recap Checklist
- Create context outside components with an explicit type and default.
- Put changing state in a provider and read it with a hook.
- Prefer props for nearby components and local state for one owner.
- Use a store for complex updates or many distant subscribers.
- Enforce authorization on the server.
Interview Questions
undefined?- Without a provider, it returns the context's default.
- A default should represent a valid fallback or an explicit missing-provider case.
- It avoids silently using a fake default.
- The hook can expose the context's non-optional value to components.
- Context is a way to provide and read values.
- Use a state hook or reducer to manage changing values.
- Split unrelated values when their update patterns differ.
- Profile before adding memoization or other optimization.
- This keeps its ownership boundary clear.
- Unrelated app areas do not need to subscribe to the same context.
- The dependency stays visible in component signatures.
- Use context when repeated forwarding becomes awkward.
- Do not use them as an authorization boundary.
- Enforce access rules on the server and keep secrets off the client.
Further Reading
- Sharing state and lifting state up covers when nearby components can share a parent as their state owner.
- Controlled inputs and forms shows when a field’s value belongs in local component state.
- Component and interaction testing covers testing the behavior of context consumers.
- Advanced state management compares context with reducers, state libraries, and query tools.
- Component boundaries and project structure explains where reusable UI and feature state can live.
- Read React’s useContext reference and guide to passing data deeply with context.
Conclusion
Start with props until the same changing value crosses several component layers. When you add context, keep its provider close to the consumers so ownership stays easy to follow.
Category
Tags
Related Posts
React State with useState and TypeScript
Learn how useState snapshots work, how TypeScript infers state types, and how to update objects and arrays immutably in React components.
Sharing State and Lifting State Up in React
Learn when sibling React components need shared state, how to lift it to their nearest common owner, and why local state often beats global state.
Accessible React UI: Semantics, Labels, and Keyboard Use
Build React interfaces with semantic controls, connected labels, visible keyboard focus, and status announcements through practical TypeScript examples.