Use API— React 19 Deep dive: Part 1
This is the first part of a series where we explore the new features introduced in React 19. Repository: https://github.com/harshq/react-19-deep-dive. Live website: https://react-19-deep-dive.lahiruek.workers.dev/
First of all, is “use” a hook?
No! It’s a function. You might notice that it’s not listed under hooks in the React documentation. (For more details, you can read the RFC here).
Introduction
const response = use(promise);
// or
const ctx = use(context);
The use
API allows you to retrieve the resolved value from a context or a promise. When used with a promise, the use
API integrates with Suspense and the closest error boundary.
Rules of use
- Should be called in Render or Hooks
The use
API can only be called in functional components or other hooks. Unlike hooks, use
can be called conditionally or inside loops (read about Rules of Hooks).
2. Promises passed to use
should be cached.
React requires that promises are cached to prevent them from being recreated on every render.
"use client"
const createNewPromise = () => fetch(`...`);
const ClientComp = () => {
...
// ❌ INFINITE LOOP. YOU'VE BEEN WARNED!!!
const response = use(createNewPromise())
...
}
If the createNewPromise
function returns a fetch(...)
, this will lead to an infinite loop. Worse, you might not even see an error.
So how do we cache promises? Currently, you need to pass a promise from a React Server Component to its child component. The child component can be either a Server Component or a Client Component. To achieve this, you’ll need a framework like Next.js or React Router v7.
3. Promises should be serializable
This rule is straightforward and applies to any prop passed from a Server Component to a Client Component.
Use cases
- Reading Context (demo)
If you have a context provider for your component, you can simply pass the context to the use
function. Since context can only be used on the client side, in a client component, you could write:
2. Streaming data from Server to Client (demo)
The use
API makes it easier to stream data directly from the server to the client by leveraging Suspense and React’s concurrent features.
First you would have a promise passed from RSC.
and then, we have use
inside the UseApiClientComponent
like this:
The use
function ensures that the Suspense fallback is rendered until the promise resolves. If there is an error, the Error Boundary will be triggered.
Stay tuned for Part 2, where we’ll explore actions
in React 19.