Sub topic 5
Reading context with use
This chapter assumes you know how to write function components and pass props. It also assumes you have used useState and useContext, and that you know what a Suspense boundary is. It does not use promises. Those are covered in the neighbouring chapters, and here the focus is context.
By the end, you will be able to read context with use, explain why it can sit after an early return, and avoid the mistakes that cause "invalid hook call" errors.
The short version
use accepts a context object and returns its current value, the same value useContext would return.
import { use } from 'react';
import { ThemeContext } from './ThemeContext';
function Label() {
const theme = use(ThemeContext);
return <span style={{ color: theme.color }}>Label</span>;
}Three behaviours are the same as useContext:
- React looks upward from the calling component for the nearest provider of that context.
- If there is no provider, you get the default value passed to
createContext. - When the provider's
valuechanges, React re-renders the components that read it.
The difference is where you are allowed to call it. useContext is a Hook and must run on every render, in the same order, at the top level of the component. use is not a Hook, even though it is called like one. React lets you call it inside if blocks, loops, and after an early return.
Why this matters
Reading context is not free of cost to your code structure. With useContext, the call has to come before any early return. That forces you to read values you may never use:
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function Heading({ children }) {
// Must run even when children is null.
const theme = useContext(ThemeContext);
if (children == null) {
return null;
}
return <h1 style={{ color: theme.color }}>{children}</h1>;
}This works, but the context read happens when it is not needed. With use, you can move the read to the place where the value is needed:
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>;
}Moving the call is mostly about readability. You keep the read next to the code that uses it. There is also a smaller performance effect, covered under "What the subscription means" below.
A complete example
The following files form a runnable example. The first creates the context with a default value.
// ThemeContext.js
import { createContext } from 'react';
export const ThemeContext = createContext({
color: 'black',
background: 'white',
});The next component reads the context after an early return.
// Heading.js
import { use } from 'react';
import { ThemeContext } from './ThemeContext';
export function Heading({ children }) {
if (children == null) {
return null;
}
const theme = use(ThemeContext);
return (
<h1 style={{ color: theme.color, background: theme.background }}>
{children}
</h1>
);
}The last file supplies the provider and a button that changes the value.
// App.js
import { useMemo, useState } from 'react';
import { ThemeContext } from './ThemeContext';
import { Heading } from './Heading';
export default function App() {
const [dark, setDark] = useState(false);
const theme = useMemo(
() =>
dark
? { color: 'white', background: '#222' }
: { color: 'black', background: 'white' },
[dark]
);
return (
<ThemeContext value={theme}>
<button onClick={() => setDark((d) => !d)}>Toggle theme</button>
<Heading>Reading context with use</Heading>
<Heading>{null}</Heading>
</ThemeContext>
);
}Things to notice:
- In React 19 you can render the context object directly as the provider:
<ThemeContext value={theme}>. The older<ThemeContext.Provider value={theme}>form still works. - The second
Headingreceivesnull, returns early, and never reads the context. - Clicking the button changes
theme. React re-renders the firstHeadingwith the new value. useMemokeeps thethemeobject stable between renders unlessdarkchanges. The reason is explained in the section on provider values.
What "not a Hook" means in practice
use has some Hook-like restrictions and some that are relaxed. This table summarizes them.
| Where you call it | `useContext` | `use` |
|---|---|---|
| Top level of a component | Allowed | Allowed |
| Top level of a custom Hook | Allowed | Allowed |
| Inside `if` / `else` | Not allowed | Allowed |
| Inside a loop | Not allowed | Allowed |
| After an early `return` | Not allowed | Allowed |
| Inside an event handler | Not allowed | Not allowed |
| Inside `useEffect`, `useMemo`, `useCallback` callbacks | Not allowed | Not allowed |
| Inside a class component | Not allowed | Not allowed |
| Inside a regular function not called from render | Not allowed | Not allowed |
The rule underneath all of this is that use must be called while React is rendering a component or a Hook. It does not need a fixed call order, which is what makes conditions and loops safe.
The linter agrees. The react-hooks/rules-of-hooks rule in eslint-plugin-react-hooks treats use as an exception and does not flag conditional calls. It still flags calls in event handlers and in callbacks passed to other Hooks.
Reading context in a loop or condition
Sometimes you need a context only for some branches. A common case is a component that behaves differently for signed-in and anonymous users:
import { createContext, use } from 'react';
export const UserContext = createContext(null);
export const PermissionsContext = createContext({ canEdit: false });
export function EditButton({ requireUser }) {
if (requireUser) {
const user = use(UserContext);
if (user == null) {
return <p>Sign in to edit.</p>;
}
}
const { canEdit } = use(PermissionsContext);
return <button disabled={!canEdit}>Edit</button>;
}The UserContext read only happens when requireUser is true. With useContext you would read it every time and ignore the result.
You can also read several contexts in a loop, for example when a component receives a list of context objects:
import { use } from 'react';
export function Summary({ contexts }) {
const values = [];
for (const context of contexts) {
values.push(use(context));
}
return <pre>{JSON.stringify(values)}</pre>;
}This is rare. If the list of contexts changes between renders, it is still valid, because use does not rely on call order. Most code should read a fixed set of contexts.
What the subscription means
When a component calls use(SomeContext), React records that the component depends on that context during that render. When the provider's value changes, React re-renders every component that read it.
Two consequences follow from the early-return pattern:
- If a render returns before calling
use, that render does not depend on the context. If the context value changes while the component is in that state, the change does not cause this component to render because of the context. - When the component's props change so that it now reaches the
usecall, the next render reads the current value.
In practice the component always shows a correct value. The saving is that components in the early-return state skip re-renders caused by context changes they do not need.
Do not rely on this as an optimization strategy. It is a side effect of putting the read where the value is needed.
Provider values and re-render storms
A context value is compared with Object.is. If the provider receives a new object on every render, every consumer re-renders, even when nothing in the object changed.
This causes the problem:
function App() {
const [dark, setDark] = useState(false);
// New object on every render of App.
return (
<ThemeContext value={{ color: dark ? 'white' : 'black' }}>
<Page />
</ThemeContext>
);
}Any state change in App creates a new object, so every use(ThemeContext) consumer re-renders. Fix it by keeping the object stable with useMemo, as in the complete example, or by hoisting constant values out of the component. Switching from useContext to use does not change this behaviour.
Default values and missing providers
createContext(defaultValue) sets the value returned when no provider is above the component. A common mistake is to treat that default as a "loading" state and then be surprised when it appears in production because a provider was left out of a test or a story.
If a missing provider is a bug in your app, make it fail loudly. Create the context with null, and wrap the read in a small custom Hook:
import { createContext, use } from 'react';
const AuthContext = createContext(null);
export function useAuth() {
const auth = use(AuthContext);
if (auth === null) {
throw new Error('useAuth must be used inside an AuthContext provider.');
}
return auth;
}
export { AuthContext };Because use allows calls after conditions, you can also read the context only when a flag is set, and still keep the guard in one place.
A custom Hook that calls use is subject to the same rule as the component: it must be called during render. Name it with the use prefix so the linter and your teammates treat it as a Hook.
Common errors
Calling `use` in an event handler
function SaveButton() {
function handleClick() {
const theme = use(ThemeContext); // Error
save(theme);
}
return <button onClick={handleClick}>Save</button>;
}React reports an invalid Hook call, because the handler runs outside of render. Read the value during render and let the handler close over it:
import { use } from 'react';
import { ThemeContext } from './ThemeContext';
function SaveButton({ save }) {
const theme = use(ThemeContext);
function handleClick() {
save(theme);
}
return <button onClick={handleClick}>Save</button>;
}Calling `use` inside `useMemo` or `useEffect`
Callbacks passed to useMemo, useEffect, and useCallback do not run as part of the component's render in the way use requires. Read the context first, then pass the value in:
import { use, useMemo } from 'react';
import { ThemeContext } from './ThemeContext';
function Swatch({ opacity }) {
const theme = use(ThemeContext);
const style = useMemo(
() => ({ color: theme.color, opacity }),
[theme.color, opacity]
);
return <div style={style}>Sample</div>;
}Calling `use` in a `try`/`catch` block
use is not supported inside try/catch. For context this rarely matters, because reading context does not throw. It matters more when you pass a promise to use, where the correct tools are error boundaries or .catch on the promise. Put the use call outside the try block, or remove the block.
Expecting a context to update without a provider change
If you mutate an object that is already the provider's value, React does not know anything changed, because Object.is still returns true. Pass a new object when the data changes.
Using `use` in a class component
Class components cannot call use. Use static contextType or <Context.Consumer> there, or convert the component to a function.
Should you replace useContext everywhere?
No. useContext still works and is not deprecated. Choose by need:
- If the read must happen unconditionally at the top, both are equal, and
useContextis fine. - If the read is only needed after an early return or inside a branch, use
use. - If you already use
usefor a promise in the same component, usingusefor context keeps one consistent style.
Mixing both in one codebase has no cost. Your team should pick a convention so readers do not have to wonder whether a difference is intended.
Summary
use(Context)returns the same value asuseContext(Context), with the same provider lookup and default value.usecan run inside conditions and loops and after early returns. It still must run during the render of a component or custom Hook.- It cannot be called in event handlers, effects, or other Hook callbacks. Read the value during render and pass it along.
- Keep provider values stable with
useMemoto avoid needless re-renders in all consumers. - Use
useContextoruseaccording to whether the read needs to be conditional. Neither is wrong.
Exercise
A component calls use(ThemeContext) after if (!visible) return null;. The provider's value changes while visible is false. What does the component render, and what value does it see once visible becomes true?
Show answer
While visible is false the component returns null and does not read the context, so the change does not cause it to re-render. When visible becomes true, the next render reaches the use call and reads the provider's current value, not the value from before the change.
Exercise
This component throws an invalid Hook call error. Explain why and show the fix. function Price({ amount }) { function format() { const locale = use(LocaleContext); return new Intl.NumberFormat(locale).format(amount); } return <button onClick={() => alert(format())}>Show price</button>; }
Show answer
The use call is inside format, which runs from a click handler and not during render. Read the context at the top of the component and let the handler close over the value: const locale = use(LocaleContext); before format, then use locale inside format.
Exercise
Your app provides <ThemeContext value={{ color }}> directly in App, which re-renders often. Every consumer re-renders on each render of App, even when color has not changed. Why, and how do you fix it?
Show answer
A new object is created on every render, and React compares context values with Object.is, so each render looks like a change. Wrap the object in useMemo with color as the dependency, for example const theme = useMemo(() => ({ color }), [color]);, and pass theme as the value.