Sub topic 14
Reading context with the use API
React 19 added a function named use. It can read a context, and it can also read a promise. This chapter covers the context case: what use(Context) does, how it differs from useContext, and where it works and where it doesn't.
This chapter assumes you know createContext, Providers, and useContext, and that you understand how a context change re-renders consumers. It also assumes you use React 19 or later. In React 18, use is not available and useContext is your only option.
What `use` does with a context
use accepts a context object, the value returned by createContext. It returns the context value, just as useContext does.
import { createContext, use } from 'react';
const ThemeContext = createContext('light');
function ThemedButton() {
const theme = use(ThemeContext);
return <button className={`btn-${theme}`}>Save</button>;
}This component behaves the same as one that calls useContext(ThemeContext).
- React finds the nearest
ThemeContext.Providerabove the component in the tree. - If there is none, it returns the default value passed to
createContext. - The component re-renders when the value of that provider changes. React compares the old and new values with
Object.is.
Everything you learned about re-renders, memoizing the value, and splitting contexts applies unchanged. use is a different way to read the same value. It does not change how the value is provided or when consumers update.
The difference from `useContext`: where you may call it
Hooks such as useContext follow the Rules of Hooks. You must call them at the top level of a component or custom hook. You can't call them inside if, loops, or after an early return. React identifies hooks by their call order, so that order must be the same on every render.
use is not a hook, even though its name starts with use. You can call it inside conditions and loops. It still has to be called while a component or a hook is rendering.
That allows code like this:
import { createContext, use } from 'react';
const ThemeContext = createContext('light');
export function Panel({ title, show, children }) {
if (!show) {
return null;
}
// Reading context after an early return is allowed with use.
const theme = use(ThemeContext);
return (
<section className={`panel-${theme}`}>
<h2>{title}</h2>
{children}
</section>
);
}With useContext, the same component would break the Rules of Hooks, because the hook would be skipped when show is false. You would have to call useContext before the if and accept that the read happens even when the component renders nothing.
Here is a loop example. Each item reads a different context, chosen by a prop:
import { createContext, use } from 'react';
const ThemeContext = createContext('light');
const LocaleContext = createContext('en');
const contexts = { theme: ThemeContext, locale: LocaleContext };
export function Settings({ keys }) {
const items = [];
for (const key of keys) {
const value = use(contexts[key]);
items.push(
<li key={key}>
{key}: {value}
</li>
);
}
return <ul>{items}</ul>;
}This is valid, but it is unusual. Most components read a fixed set of contexts, and for those either API is fine.
What `use` still cannot do
The relaxed rule is narrow. Calls to use still have to happen during rendering.
- Don't call it in an event handler. If a click handler needs a context value, read the value during render and let the handler close over it.
- Don't call it inside
useEffect,useMemo,useCallback, or any other callback that React runs outside the render pass. - Don't call it in a plain function that isn't called from a component or hook.
- Don't call it in a
try/catchblock. This restriction exists mainly for promises, but the safe habit is to read context outsidetry.
The following component shows the right pattern for a click handler:
import { createContext, use } from 'react';
const AnalyticsContext = createContext({ track: () => {} });
export function BuyButton({ productId }) {
// Read during render...
const analytics = use(AnalyticsContext);
function handleClick() {
// ...and use the value later, inside the handler.
analytics.track('buy', { productId });
}
return <button onClick={handleClick}>Buy</button>;
}Using `use` in a custom hook
The provider-plus-custom-hook pattern from earlier chapters works the same way. Swap useContext for use in the accessor:
import { createContext, use, useCallback, useMemo, useState } from 'react';
const AuthContext = createContext(null);
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const login = useCallback((name) => setUser({ name }), []);
const logout = useCallback(() => setUser(null), []);
const value = useMemo(() => ({ user, login, logout }), [user, login, logout]);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth() {
const ctx = use(AuthContext);
if (ctx === null) {
throw new Error('useAuth must be used inside <AuthProvider>');
}
return ctx;
}Because use is allowed in conditions, you can also write a variant that reads context only when needed:
export function UserBadge({ anonymous }) {
if (anonymous) {
return <span>Guest</span>;
}
const { user } = useAuth();
return <span>{user ? user.name : 'Signed out'}</span>;
}The call to useAuth here comes after a conditional return. This is only legal because useAuth calls use internally and no other hook. If useAuth called useContext or any other hook, React's hook rules would apply to it. Don't rely on this pattern in shared code. A custom hook named useAuth looks like a hook, so a reader (and a linter) will assume it is called unconditionally. A better habit is to keep the hook call at the top and branch afterwards, unless skipping the read is really valuable.
Comparing the two APIs
| Aspect | `useContext(Ctx)` | `use(Ctx)` |
|---|---|---|
| Available in | React 16.8 and later | React 19 and later |
| Is a hook | Yes | No |
| Allowed in `if`, loops, after early return | No | Yes |
| Value returned | Nearest provider value or default | Same |
| Re-render when provider value changes | Yes | Yes |
| Also accepts a promise | No | Yes |
| Works in event handlers or effects | No | No |
The promise case in one paragraph
use can also take a promise. If the promise is still pending, React suspends the component and shows the nearest Suspense fallback. When the promise resolves, React re-renders and use returns the result. If it rejects, the nearest error boundary handles it. Context and promises combine well when a provider shares a promise instead of a loaded value, so that many components can wait on the same request. The promise must be stable across renders. Creating a new promise inside a client component's render makes React see a new promise every time, and it can loop. Create it in a Server Component, a cache, or a state initializer that runs once.
Choosing between `useContext` and `use`
Both APIs are supported. You do not need to migrate existing code.
- Keep
useContextin code that has to run on React 18 or earlier, such as shared libraries. - Prefer
usewhen you want to read context after an early return, so that components that render nothing don't subscribe to it. - Prefer one API per codebase for the common top-level read. Mixing them without a reason makes reviews harder.
- Remember that the optimization is small. A skipped read saves very little work. The main gain is code that matches the shape of the logic.
One edge case is worth knowing. A component that never reads a context does not subscribe to it. If use(ThemeContext) runs only after an early return, then on renders where the early return happens, the component is not a consumer for that render. A change to the theme will not matter to it in that state. When show becomes true, the component renders again and reads the current value.
Common errors
- Calling
usein an event handler. React throws an error saying thatusewas called outside of a component or hook. Read during render and capture the value. - Passing the Provider instead of the context. The argument must be the object from
createContext, such asThemeContext, notThemeContext.Provider. - Expecting a missing provider to throw. As with
useContext, you get the default value. Keep thenulldefault and the explicit check shown in the custom hook above if you want a clear error. - Running on React 18.
usewill beundefinedor missing from the import, and the app fails at runtime or build time. Check your installed version.
Exercise
A component renders null when its visible prop is false, and otherwise shows text styled by ThemeContext. Write the component using use so that it reads the context only when visible is true. Then explain why the same structure would be a mistake with useContext.
Show answer
Example: function Label({ visible, text }) { if (!visible) return null; const theme = use(ThemeContext); return <p className={label-${theme}}>{text}</p>; }. With useContext this breaks the Rules of Hooks, because the hook call would be skipped on renders where visible is false. React relies on hooks running in the same order on every render, so a conditional hook call can corrupt state and triggers a lint error. use is not a hook, so React allows it after an early return.
Exercise
Why does this code fail, and how do you fix it? function SaveButton() { const handleClick = () => { const user = use(UserContext); save(user); }; return <button onClick={handleClick}>Save</button>; }
Show answer
use must be called while the component renders, and an event handler runs later, outside the render pass. Read the context at the top of the component with const user = use(UserContext); and let handleClick call save(user) using that value.