React Reference ยท Performance and Concurrency Hooks
React use API
Reference for React use(): read a promise or a context during render, call it conditionally or in loops, and understand why the promise must be stable.
use is a React API (written like a hook, but with relaxed rules) that reads the value of a resource during render. It accepts two kinds of resources: a context, which gives the same result as useContext, and a promise (or any thenable), which suspends the component until the promise resolves and then returns the resolved value.
Unlike hooks, use may be called inside if statements, loops and after an early return. It still has to be called while a component or hook is rendering.
const theme = use(ThemeContext); const user = use(userPromise);
Try it
useContext could not do this: hooks must run on every render in the same order.
The promise is created outside the component, so every render sees the same one. See use with Suspense for caching a promise per key.
Syntax
const value = use(resource); // resource: Context<T> | Promise<T> (any thenable) // TypeScript: use<T>(usable: Usable<T>): T
| Name | Description |
|---|---|
resource |
A context object created with createContext, or a promise/thenable. |
Returns: for a context, its current value (the nearest provider's, or the default). For a promise, the value it resolved with.
Errors / edge cases: if the promise is pending, the component suspends and the nearest <Suspense> shows its fallback. If it rejects, the error is thrown during render and caught by the nearest error boundary. Calling use inside try/catch is not supported, because the suspend signal would be swallowed.
Usage notes
- The promise must be stable. Creating a promise inside a Client Component's render gives a new promise every time, so the component suspends forever. Create it outside, cache it, or pass it down from a Server Component.
- Server to client. A Server Component can start a fetch and pass the promise as a prop; the Client Component reads it with
use. - Not for events.
useonly works in render, never in event handlers or effects. asynccomponents are only valid as Server Components; in Client Components useuseinstead ofawait.- Handling rejection without a boundary: attach
.catch()to the promise to turn errors into a fallback value before passing it touse. - Context version reads like
useContextand, unlike it, can sit behind a condition. - Added in React 19.
Related
- use with Suspense,
<Suspense>,useContext,cache - Lessons: use and Suspense, Context