Sub topic 1
What use does and how it differs from other Hooks
React 19 added use, a function that reads a value from a resource while a component renders. The resource can be a promise or a context. This chapter explains what use does, how it differs from useContext, useState, and useEffect, and which rules apply to it. Later chapters cover the details of promises, error handling, and Server Components.
Prerequisites
This chapter assumes you already know the following:
- How to write function components and pass props to them.
- Basic use of
useStateanduseContext, including creating a context and wrapping a tree in a provider. - How JavaScript promises work: pending, fulfilled, and rejected states, and how
asyncfunctions return promises. - A general idea of what
<Suspense>does. It shows a fallback while something below it is not ready. The next chapter covers it in more detail.
The examples use React 19 and JSX. Only React 19 and later export use, so check your installed version first.
What use does
use takes one argument, a resource, and returns the value that resource holds. React 19 supports two kinds of resource:
- A promise.
usereturns the promise's fulfilled value. While the promise is pending,usesuspends the component. If the promise rejects,usethrows the rejection reason during render. - A context.
usereturns the context's current value, the same valueuseContextwould return.
The signature is small:
const value = use(resource);Suspending means the component stops rendering at that line. React shows the nearest <Suspense> fallback above it. When the promise settles, React renders the component again, and use returns the value. Everything after the use call runs only once the value exists, so you never write if (data === null) checks for loading.
Here is a complete example. The promise is created once, outside any component, so every render sees the same promise.
import { Suspense, use } from 'react';
const greetingPromise = new Promise((resolve) => {
setTimeout(() => resolve('Hello from a promise'), 1000);
});
function Greeting() {
const text = use(greetingPromise);
return <p>{text}</p>;
}
export default function App() {
return (
<Suspense fallback={<p>Loading greeting...</p>}>
<Greeting />
</Suspense>
);
}For the first second, the page shows "Loading greeting...". After that, Greeting renders with the resolved text.
How use differs from other Hooks
use is often called a Hook, and React's documentation does call it an API. It is not a Hook in every sense. The name starts with use, and you call it from components and custom Hooks during render. The difference is that it is exempt from the rule that Hooks must run unconditionally and in the same order.
The older Hooks store state or register work by their position in the component's call order. React keeps an internal list of Hook slots, and the first useState call always maps to slot one. If a call is skipped on one render, every later call lands in the wrong slot. That is why the Rules of Hooks forbid conditions, loops, and early returns before a Hook.
use does not rely on a slot for what it reads. A promise is an object you pass in, and the context is identified by the context object. React can therefore read the value wherever the call happens. This table compares the related tools.
| Tool | Reads | Allowed in conditions and loops | Allowed after an early return | Suspends the component |
|---|---|---|---|---|
| `useContext` | A context | No | No | No |
| `useState` | Local state | No | No | No |
| `useEffect` | Nothing, it runs side effects after render | No | No | No |
| `use` with a context | A context | Yes | Yes | No |
| `use` with a promise | A promise's result | Yes | Yes | Yes, while pending |
Two other differences matter in practice.
First, use does not store anything. It has no setter, no initial value, and no cleanup. If you need data that changes in response to user actions, you still need useState or useReducer. use only reads a value that something else produced.
Second, use is not a way to start asynchronous work. useEffect runs after the component has rendered, so you can start a fetch there and store the result in state. use runs during render and only reads a promise that already exists. Where that promise comes from is the main design question when you adopt use. A later chapter covers it.
Reading context with use
use(SomeContext) returns the same value as useContext(SomeContext). React finds the nearest matching provider above the component in the tree. If there is none, you get the context's default value. The component re-renders when the provider's value changes, as it would with useContext.
The extra freedom is where you can call it. This example reads the theme only for the branch that needs it.
import { createContext, use } from 'react';
const ThemeContext = createContext({ color: 'black' });
function Heading({ children }) {
if (children == null) {
return null;
}
const theme = use(ThemeContext);
return <h1 style={{ color: theme.color }}>{children}</h1>;
}
export default function App() {
return (
<ThemeContext value={{ color: 'rebeccapurple' }}>
<Heading>Hello</Heading>
<Heading />
</ThemeContext>
);
}Three things in this example are worth noting:
Headingreturns early when it has no children. WithuseContext, you would have to call it above the early return, or the linter would reject the code. Withuse, the call can sit where it is needed.- In React 19 you can render the context object itself as the provider, as
<ThemeContext value={...}>. The older<ThemeContext.Provider>form still works. - The second
<Heading />has no children, so it never callsuse.
Reading context conditionally does not change how React tracks the subscription. If a render reads the context, React treats the component as dependent on it for that render. If a render skips the call, a change in the context value will not cause extra work for that render. Most of the time this is a small saving. It matters more when a component with expensive logic can bail out before reaching the context read.
Use useContext when you read context unconditionally at the top of a component. Both give the same result, and useContext is still fully supported. The reasons to choose one over the other are covered in the last chapter.
Where use can be called
Because use is exempt from the ordering rule, these patterns all work:
- Inside an
iforelsebranch. - Inside a
fororwhileloop, or inside a.map()callback that runs during render. - After an early
return. - Inside a custom Hook, when that Hook is called from a component.
The following restrictions still apply:
- Only during render. You must call
usefrom a component function or a custom Hook. You cannot call it from an event handler, auseEffectcallback, asetTimeoutcallback, or a plain utility function that React is not rendering. In an event handler, you want the value of a promise after a click, andawaitin anasynchandler is the right tool. - Not inside
try/catch. React implements suspending by throwing internally, and atry/catchblock would intercept that throw. Handle rejected promises with an error boundary or by attaching.catch()to the promise before you pass it in. The error handling chapter shows both. - Not in a class component. Class components cannot call
use. They usestatic contextTypeorContext.Consumerfor context.
A loop example shows the flexibility. A component receives an array of promises and renders each one's value:
import { Suspense, use } from 'react';
const promises = [
new Promise((resolve) => setTimeout(() => resolve('first'), 500)),
new Promise((resolve) => setTimeout(() => resolve('second'), 1500)),
];
function List({ items }) {
const rows = [];
for (const item of items) {
rows.push(<li key={rows.length}>{use(item)}</li>);
}
return <ul>{rows}</ul>;
}
export default function App() {
return (
<Suspense fallback={<p>Loading list...</p>}>
<List items={promises} />
</Suspense>
);
}Reading several promises one after another in the same component creates a waterfall. List suspends on the first promise, and React retries the render when it resolves. Only then does the loop reach the second use. In this example both promises were created before rendering, so their timers are already running in parallel and the total wait is about 1.5 seconds. If each promise were created only after the previous one resolved, the waits would add up. Start independent requests early, ideally before the component renders, so they run in parallel.
What happens to a suspended component
Suspending is not an error, and it does not unmount the whole app. React stops rendering the suspended component and finds the nearest <Suspense> boundary above it. That boundary shows its fallback in place of its children. Components outside the boundary keep rendering normally.
Several details affect how you design components around use:
- State on first mount is not preserved. If a component suspends during its first render, React discards the work done so far. Nothing from that attempt, including state, is kept. The retry starts from scratch. Keep the code before
usefree of side effects. - Effects do not run for the suspended attempt.
useEffectruns after React commits a render to the screen. A render that suspends never commits, so its effects never run. - Already-visible content can stay on screen. When a state update suspends inside a transition (
startTransitionoruseTransition), React can keep showing the old UI instead of the fallback. Without a transition, the boundary swaps to its fallback. - If no boundary exists, React uses the root as the boundary and the whole page waits. Always place a
<Suspense>boundary at a spot where a loading placeholder makes sense to the user.
Because the component code runs again after the promise resolves, the code above the use call executes more than once. That is the same reason render code must be pure in any React component.
Common errors
These are the mistakes people most often make when they first adopt use.
- Creating the promise during render in a Client Component. Writing
use(fetch('/api/items').then((r) => r.json()))inside a Client Component makes a new promise on every render. React cannot tell the new promise is the same request, so it suspends again, and the cycle repeats. React warns that the component was suspended by an uncached promise. The fix is to create the promise outside the component, in a parent, in a cache, or in a Server Component. The chapter on promise stability covers this in detail. - Wrapping
useintry/catch. Thecatchblock never sees the rejection, and the suspend mechanism breaks. Use an error boundary instead. - Calling
usein an event handler or effect. React throws an error telling you thatusewas called outside a component or Hook. Move the read into render, orawaitthe promise in the handler. - Forgetting a
<Suspense>boundary. The page stays blank or the whole root waits. Add a boundary close to the component that reads the promise. - Passing something that is not a promise or context.
use(5)oruse(someObject)is not supported. A plain value needs nouseat all. - Expecting
useto hold state. It returns what the resource contains and nothing else. UseuseStatefor values the user can change.
Summary of the model
You can hold the whole idea in three statements:
use(resource)returns the value inside a promise or context while the component renders.- For a promise,
useconverts "not ready" into suspending and "failed" into a thrown error, so the component body only handles the success case. useis exempt from the Hook ordering rule because it keeps no position-based state, but it must still be called during render and never insidetry/catch.
Exercise
A component calls useContext(ThemeContext) after an if (!user) return null; line, and the linter reports a Rules of Hooks violation. Rewrite the line so it is allowed, and explain why the change is legal.
Show answer
Replace the call with const theme = use(ThemeContext); and import use from 'react'. useContext is an ordinary Hook, which React tracks by its position in the call order, so it cannot sit after an early return. use does not depend on a position-based slot, so it may appear after a condition or early return. It must still be called during render from a component or custom Hook.
Exercise
A teammate writes function Profile() { const user = use(fetch('/api/user').then((r) => r.json())); return <p>{user.name}</p>; } inside a Client Component wrapped in <Suspense>. The page flickers between the fallback and nothing, and React logs a warning about an uncached promise. What is wrong, and what is one fix?
Show answer
The component creates a new promise on every render. Each retry produces another new, pending promise, so the component suspends again and never settles. One fix is to create the promise outside the component, for example in a parent or Server Component, and pass it in as a prop: function Profile({ userPromise }) { const user = use(userPromise); ... }. The promise then keeps the same identity across renders.
Exercise
Why does the following code fail, and how would you handle a rejected promise correctly? function Message({ promise }) { try { const text = use(promise); return <p>{text}</p>; } catch { return <p>Failed</p>; } }
Show answer
use is not supported inside try/catch. React suspends by throwing internally, and the catch block interferes with that. Wrap the component in an error boundary so the nearest boundary renders the fallback when use throws the rejection. Alternatively, attach .catch(() => 'default value') to the promise before passing it in, so it always fulfills.