Sub topic 6
Sharing state with context
This chapter assumes you can write function components, use useState, and pass functions as props. It covers the Context API: what it does, how React resolves it, and the mistakes that cause bugs and extra renders. Later chapters build compound components on top of it.
The problem context solves
When state lives in a parent and a deeply nested child needs it, you can pass it down as props through every layer. This is called prop drilling. Components in the middle receive props they never use, and every new value means editing each layer.
Context lets a component publish a value that any descendant can read directly. The components in between do not need to know about it.
The three parts
Context has three parts:
createContext(defaultValue)creates a context object.<Context.Provider value={...}>makes a value available to everything rendered inside it.useContext(Context)reads the value from the nearest provider above the calling component.
The following example shares a theme. The provider owns the state, and a custom hook wraps the read.
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext(null);
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
const ctx = useContext(ThemeContext);
if (ctx === null) {
throw new Error('useTheme must be used inside <ThemeProvider>');
}
return ctx;
}
function ThemeButton() {
const { theme, setTheme } = useTheme();
const next = theme === 'light' ? 'dark' : 'light';
return <button onClick={() => setTheme(next)}>Switch to {next}</button>;
}
export function App() {
return (
<ThemeProvider>
<main>
<ThemeButton />
</main>
</ThemeProvider>
);
}ThemeButton sits inside main, which passes no props. The button still reads and updates the theme. Because the provider holds state with useState, calling setTheme re-renders the provider, and React then updates every consumer.
How React resolves a context value
useContext looks upward from the calling component and returns the value of the nearest matching provider. Three consequences follow:
- Providers can be nested. The inner one wins for its subtree, so you can override a theme for one section of the page.
- If no provider is found, you get the default passed to
createContext. This default is not the provider's initial state. It is only a fallback for components rendered outside any provider. - A component that calls
useContextre-renders whenever the provider'svaluechanges. React compares the old and new value withObject.is.
The diagram shows the flow of data and updates.
Why a null default and a guard
The example uses null as the default and throws in the hook. Without the guard, a component rendered outside the provider would get null and fail later with an unclear message such as "cannot destructure property 'theme' of null". The guard fails early and names the cause. Compound components use the same guard to catch subcomponents used outside their parent.
If your context has a sensible default without a provider, such as a default locale, a real default value is fine. Use the null-and-throw version when a provider is required.
The identity pitfall
The provider in the first example writes value={{ theme, setTheme }}. That creates a new object on every render of ThemeProvider. Since Object.is sees a different object each time, every consumer re-renders whenever the provider re-renders, even if theme did not change. This happens, for example, when the provider's own parent re-renders.
Memoize the value so its identity changes only when its contents do:
import { createContext, useContext, useMemo, useState } from 'react';
const ThemeContext = createContext(null);
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const value = useMemo(() => ({ theme, setTheme }), [theme]);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
export function useTheme() {
const ctx = useContext(ThemeContext);
if (ctx === null) {
throw new Error('useTheme must be used inside <ThemeProvider>');
}
return ctx;
}setTheme from useState has a stable identity, so it does not need to be in the dependency array. A function you define yourself inside the provider is recreated on each render. Wrap it in useCallback and list it in the dependencies if you put it in the value.
Splitting state from actions
Components that only trigger updates do not need to re-render when the state changes. A common fix is two contexts: one for the changing state and one for stable actions.
import { createContext, useContext, useMemo, useState } from 'react';
const CountStateContext = createContext(null);
const CountActionsContext = createContext(null);
export function CountProvider({ children }) {
const [count, setCount] = useState(0);
const actions = useMemo(
() => ({
increment: () => setCount((c) => c + 1),
reset: () => setCount(0),
}),
[]
);
return (
<CountActionsContext.Provider value={actions}>
<CountStateContext.Provider value={count}>
{children}
</CountStateContext.Provider>
</CountActionsContext.Provider>
);
}
export function useCount() {
const count = useContext(CountStateContext);
if (count === null) {
throw new Error('useCount must be used inside <CountProvider>');
}
return count;
}
export function useCountActions() {
const actions = useContext(CountActionsContext);
if (actions === null) {
throw new Error('useCountActions must be used inside <CountProvider>');
}
return actions;
}The actions object is created once, because its functions use the updater form of setCount and need no outside values. A component that only calls useCountActions() never re-renders when count changes. Note that count starts at 0, not null, so the null check still works as a "no provider" test.
Limits and common errors
- Context is not a full state manager. It transports a value. It has no selectors, so a consumer of a large object re-renders when any field changes. If one context holds many unrelated fields, split it by how often each field changes and who reads it.
- Using context for everything. If only a parent and its direct child share state, props are simpler and easier to trace. Context hides the data flow. Use it when the value crosses several layers or when sibling-level coordination needs implicit sharing, as in compound components.
- Providers placed too high. Putting a frequently changing provider at the app root re-renders all of its consumers on every change. Place the provider as close as possible to the components that need it.
- Stale default confusion. Changing the
createContextdefault does not change what a mounted provider supplies. - Missing
childrenhandling. A provider must renderchildren. If it returns only theProviderelement without them, nothing below it renders.
Exercises
Exercise
A UserProvider renders <UserContext.Provider value={{ user, logout }}> where logout is a function defined inside the provider body. Consumers re-render every time the provider's parent re-renders, even when user is unchanged. Why does this happen, and how do you fix it?
Show answer
The { user, logout } object literal is new on each render, and logout is also recreated each render. Object.is sees a different value, so every consumer re-renders. Wrap logout in useCallback with the right dependencies, then build the value with useMemo(() => ({ user, logout }), [user, logout]).
Exercise
What does useContext return when a component is rendered outside any provider, and why do many custom hooks throw an error in that case?
Show answer
It returns the default value passed to createContext. If that default is null, the component would get null and fail later with a confusing error. A guard in the custom hook throws immediately with a message that names the missing provider.