Sub topic 6
Sharing state with context
This chapter assumes you know function components, props, useState, and passing functions as props. It covers the Context API, which later chapters use to build compound components.
The problem context solves
Lifting state up works until the state must pass through many layers. If a component three levels down needs a value, every component in between has to accept it and pass it along, even if it never uses it. This is called prop drilling.
Context lets a component publish a value to everything below it in the tree. Any descendant can read the value directly, without props.
The three parts
createContext(defaultValue)creates a context object.<Context.Provider value={...}>makes a value available to its descendants.useContext(Context)reads the value from the nearest Provider above the calling component.
A working example
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) {
throw new Error('useTheme must be used inside <ThemeProvider>');
}
return ctx;
}
function ThemeButton() {
const { theme, setTheme } = useTheme();
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Current theme: {theme}
</button>
);
}
function Toolbar() {
return <ThemeButton />;
}
export default function App() {
return (
<ThemeProvider>
<Toolbar />
</ThemeProvider>
);
}Toolbar receives no props, yet ThemeButton reads and updates the theme. The state lives in ThemeProvider, so changing it re-renders the Provider and every component that calls useContext for that context.
Wrap context in a custom hook
The example exports useTheme instead of the raw context. This gives you two benefits:
- Consumers do not import the context object, so you can change its shape later.
- The hook can throw a clear error when it runs outside a Provider. Without the guard, the default
nullleads to a confusing "cannot destructure" error.
The Tabs example in a later chapter uses this same guard.
Common errors
- A new object on every render. Writing
value={{ theme, setTheme }}creates a new object each time the Provider renders. Every consumer then re-renders, even ifthemedid not change. Memoize the value withuseMemo, as above. - Using context for fast-changing state. Every consumer re-renders when the value changes. Keep context for values that change rarely, such as theme, the current user, or a compound component's selected item. Do not use it for something like mouse position.
- Reaching for context too early. If the state only passes through one or two layers, props are simpler and easier to trace. Passing
childrencan also remove the need to drill, because the parent can render the deep component itself.
Exercise
A Provider uses value={{ count, increment }} and its parent re-renders often for unrelated reasons, while count stays the same. Why do context consumers still re-render, and how do you fix it?
Show answer
Each render creates a new object, so the value changes by reference and React re-renders every consumer. Wrap the value in useMemo with [count, increment] as dependencies (and wrap increment in useCallback if it is defined inside the component), so the reference stays the same until count changes.