Sub topic 5
Reading context with useContext
This chapter covers how useContext reads a context value, how React decides which value a component gets, and the errors people most often hit. It assumes you know JavaScript ES6 syntax, React function components, JSX, props, and the useState hook. It also assumes you know that React re-renders a component when its state or props change.
By the end you should be able to read a context from any component, predict which value it receives, and spot the common mistakes before they cost you an afternoon.
The shape of the call
useContext is a hook that takes a context object and returns the current value of that context for the calling component.
const value = useContext(SomeContext);The argument is the context object itself, the thing createContext returned. It is not the Provider, not the Consumer, and not the string name of the context. The return value is whatever the nearest matching Provider above the component passed in its value prop. If there is no such Provider, the return value is the default value given to createContext.
Like every hook, useContext must be called at the top level of a function component or of another hook. Do not call it inside loops, conditions, or event handlers. The one exception is the use API, covered at the end of the full tutorial.
A complete example
The following example creates a context, provides a value from App, and reads it two levels down. Toolbar does not receive or forward any props.
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<Toolbar />
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle theme
</button>
</ThemeContext.Provider>
);
}
function Toolbar() {
return <ThemedButton />;
}
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={`btn-${theme}`}>Save</button>;
}Three things happen here:
createContext('light')creates the context and sets'light'as the default.AppwrapsToolbarinThemeContext.Providerand passes the currentthemestate asvalue.ThemedButtoncallsuseContext(ThemeContext)and gets thethemevalue fromApp, even thoughToolbarsits between them and knows nothing about it.
When you click the toggle button, App updates its state and re-renders. The Provider receives a new value. React then re-renders ThemedButton, because it reads that context.
How React finds the value
React does not search the component tree at call time by scanning your code. When a component renders, useContext looks upward through the component's ancestors in the rendered tree and takes the value from the closest Provider for that specific context object.
The diagram below shows the lookup for a component with two ancestors providing the same context.
Two rules follow from this.
- The lookup is by context object identity. Two contexts created by two separate
createContextcalls never interfere, even if they hold the same kind of data and have the same name. - The lookup depends on where the component appears in the tree, not where it is defined in your source files. A component defined next to
Appbut rendered outside the Provider gets the default value.
Reading context in different places
Any function component or custom hook beneath a Provider can call useContext. That includes components far from the Provider and components that receive no props at all.
You can read several contexts in one component. Each call is independent:
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
const LocaleContext = createContext('en');
function PriceTag({ amount }) {
const theme = useContext(ThemeContext);
const locale = useContext(LocaleContext);
const text = new Intl.NumberFormat(locale, {
style: 'currency',
currency: 'USD',
}).format(amount);
return <span className={`price-${theme}`}>{text}</span>;
}You can also call useContext inside your own hook. This is the basis of the custom-hook pattern covered in a later chapter. It lets components read context without importing the context object directly.
Reading context passed through a Provider that renders children
A Provider only affects components rendered inside it. Consider this structure:
function Page() {
return (
<ThemeContext.Provider value="dark">
<Sidebar />
</ThemeContext.Provider>
);
}
function Footer() {
const theme = useContext(ThemeContext);
return <footer>{theme}</footer>;
}If Footer is rendered as a sibling of Page, or anywhere outside the Provider, it reads 'light' (the default), not 'dark'. A frequent mistake is to place the Provider too low in the tree, so that some consumers fall outside it. The fix is to move the Provider up so that it wraps every component that needs the value.
Re-rendering when the value changes
When the value prop of a Provider changes, React re-renders every component under it that called useContext for that context. React compares the old and new values with Object.is. If they are the same, consumers are not re-rendered because of the context.
This has a subtle consequence for objects. Passing a new object literal on every render makes the value look different every time:
function App() {
const [user, setUser] = useState(null);
return (
<UserContext.Provider value={{ user, setUser }}>
<Main />
</UserContext.Provider>
);
}Each time App renders, { user, setUser } is a new object, so every consumer re-renders, even if user did not change. A later chapter covers fixing this with useMemo. For now, remember that what you pass as value decides how often consumers update.
A consumer also re-renders when its own parent re-renders, as any component does. The context rule is an extra trigger, not a replacement for normal rendering.
Common errors
Passing the wrong thing to useContext
// Wrong: passes the Provider
const theme = useContext(ThemeContext.Provider);
// Right: passes the context object
const theme = useContext(ThemeContext);If you pass the wrong object, you get a warning or an unexpected value rather than your data.
Getting the default value when you expected a Provider value
If useContext returns the default, no Provider for that context is above the component. Check these causes in order:
- The Provider is missing or placed too low in the tree.
- The Provider uses a different context object, for example because two files each called
createContextfor the same idea. - The Provider imports from a different copy of the module, such as a duplicated package in a monorepo.
Reading a property of `null`
A common pattern is createContext(null) with a Provider that passes an object. A component outside the Provider then reads null, and ctx.user throws Cannot read properties of null. Guard against this with a custom hook that throws a clear message, which a later chapter shows.
Forgetting the `value` prop
<ThemeContext.Provider>
<Toolbar />
</ThemeContext.Provider>Without value, consumers receive undefined, not the default. The default is used only when there is no Provider at all.
Expecting a child to update a parent's context
useContext is read-only. It gives a component the value. To change shared state, the Provider's value must include a way to change it, such as a setter function from useState or a dispatch function from useReducer.
Quick reference
| Situation | What `useContext` returns |
|---|---|
| One Provider above, `value="dark"` | `"dark"` |
| Two nested Providers for the same context | The value from the closer one |
| No Provider above | The default passed to `createContext` |
| Provider above with no `value` prop | `undefined` |
| Provider for a different context object | The default of the context you asked for |
Practice
Exercise
A component calls useContext(LevelContext). LevelContext was created with createContext(0). The tree is <LevelContext.Provider value={2}><A /></LevelContext.Provider> and <B /> rendered as a sibling of that Provider. Which values do A and B read?
Show answer
A reads 2, the value from the nearest Provider above it. B is outside the Provider, so it reads the default value, 0.
Exercise
A Provider is written as <AuthContext.Provider> with no value prop, and the context was created with createContext({ user: 'guest' }). A consumer reads useContext(AuthContext).user. What happens, and why?
Show answer
It throws a TypeError. A Provider with no value prop supplies undefined, and the default is used only when no Provider exists. Reading .user on undefined fails. The fix is to pass a value to the Provider.