Sub topic 5
Reading context with use
This chapter assumes you know function components and props, basic useState and useContext, and what a context provider is. Earlier chapters covered reading promises with use and the rules for where use can be called. Here we apply those rules to context.
What `use(Context)` does
use accepts a context object, such as one made with createContext. It returns the value from the nearest matching provider above the component. If there is no provider, it returns the context's default value.
The result is the same as useContext. Both subscribe the component to the context, so it re-renders when the provider's value changes.
import { createContext, use } from 'react';
const ThemeContext = createContext({ color: 'black' });
function Label({ text }) {
const theme = use(ThemeContext);
return <span style={{ color: theme.color }}>{text}</span>;
}Here Label gets { color: 'black' } when no provider wraps it. Inside <ThemeContext value={...}> it gets the provided value.
Why use `use` instead of `useContext`
useContext is a Hook, so it must run on every render in the same order. You can't call it after a condition or an early return.
use is not bound by that rule. You can call it inside if statements and loops, and after an early return. That lets you read context only on the paths that need it.
import { use } from 'react';
import { ThemeContext } from './ThemeContext';
function Heading({ children }) {
if (children == null) {
return null;
}
const theme = use(ThemeContext);
return <h1 style={{ color: theme.color }}>{children}</h1>;
}When children is null, Heading returns before it touches the context. Calling useContext at that point would break the Rules of Hooks. The linter would report it, and React could mismatch Hook state between renders.
The same applies to loops and conditional branches:
import { use } from 'react';
import { ThemeContext } from './ThemeContext';
import { DensityContext } from './DensityContext';
function Row({ compact, children }) {
let padding = 12;
if (compact) {
const density = use(DensityContext);
padding = density.padding;
}
const theme = use(ThemeContext);
return (
<div style={{ padding, color: theme.color }}>{children}</div>
);
}Row reads DensityContext only when compact is true. It always reads ThemeContext.
What stays the same
Conditional calls do not change how context works. These points still hold:
- Provider lookup.
usefinds the nearest provider above the calling component, not one inside it. - Re-rendering. A component that calls
use(Context)re-renders when the provided value changes, even if the call is conditional. On a render where the call is skipped, the component has no dependency on that context. - Render only. You still call
usewhile rendering, inside a component or a custom Hook. Calling it inside an event handler or an effect is an error.
function SaveButton() {
function handleClick() {
// Wrong: use cannot be called in an event handler.
const theme = use(ThemeContext);
}
return <button onClick={handleClick}>Save</button>;
}To use the value in a handler, read it during render and let the handler close over it:
function SaveButton() {
const theme = use(ThemeContext);
function handleClick() {
console.log('Saving with', theme.color);
}
return <button onClick={handleClick}>Save</button>;
}Where the call can go
The following diagram shows the decision for a call to use.
Choosing between the two
For context, the two calls give the same value. Use this table to pick one.
| Situation | Prefer |
|---|---|
| Context is read on every render | Either. `useContext` is the established form. |
| Context is read only after a condition or early return | `use` |
| Context is read inside a loop | `use` |
| Code must also run on React versions before 19 | `useContext` |
use for context is available in React 19. Older versions don't include it, so check your React version before relying on it.
Common mistakes
- Calling
usein a handler or effect. Read the value during render and pass it down through a closure or a dependency. - Wrapping
useintry/catch. React does not support this. The chapter on rejected promises shows how to handle errors with an error boundary instead. - Expecting a provider where there is none. If you forget the provider,
usereturns the default value passed tocreateContext. A default ofnullthen causes aTypeErrorwhen you readtheme.color. - Passing a new object as the provider value each render. Every consumer re-renders whenever the parent renders, because the value is a new object each time. Keep the value stable with
useMemoor state when consumers are costly to render.
Exercise
A component starts with if (!user) return null; and then needs AuthContext to render a menu. Why does use(AuthContext) work after the early return but useContext(AuthContext) doesn't, and what does the component do when user is missing?
Show answer
useContext is a Hook and must be called in the same order on every render, so calling it after an early return breaks the Rules of Hooks. use is exempt from that rule and can be called after a condition or early return. When user is missing, the component returns null before reaching use, so it reads no context on that render and has no dependency on AuthContext for that render.
Exercise
Given const theme = use(ThemeContext); and no ThemeContext provider above the component, what value does theme hold?
Show answer
It holds the default value passed to createContext(defaultValue). If no default was given, it is undefined.