Sub topic 8
Streaming Data from a Server Component to a Client Component
A Server Component can start a data request and hand the unfinished promise to a Client Component, which reads it with use. The server then sends the rest of the page right away. The data follows when it is ready. This chapter covers how that works, what the promise looks like on the client, and the mistakes that cause trouble.
What you should already know
This chapter assumes you have these skills from earlier chapters or from your own work:
- You can read a promise with
useinside aSuspenseboundary. - You know why a promise must keep the same identity across renders.
- You can handle a rejected promise with an error boundary or a fallback value.
- You know that React Server Components run only on the server, and that files with
'use client'at the top define Client Components.
The examples assume a framework that supports Server Components, such as the Next.js App Router. The pattern is the same in any such framework.
The problem: an awaited fetch blocks the page
A Server Component can be an async function. You can await data inside it, and that is often the right choice. The cost is that the component produces no output until the await finishes. Everything below it in the tree waits as well, unless something above it provides a Suspense boundary.
// app/page.jsx (a Server Component)
import { getMessage } from '../lib/messages';
export default async function Page() {
const message = await getMessage(); // nothing renders past this line yet
return (
<main>
<h1>Inbox</h1>
<p>Here is the message: {message}</p>
</main>
);
}If getMessage takes two seconds, the user sees nothing from this page for two seconds. The <h1> does not depend on the message, but it waits anyway.
You can fix this by moving the data-dependent part into its own async Server Component and wrapping it in Suspense. That works well. Passing the promise down is a second option. It fits best when a Client Component needs the data, for example because it also holds state or handles events.
Passing the promise instead of the value
The change has two parts. In the Server Component, call the async function but do not await it. Pass the pending promise to a Client Component as a prop. In the Client Component, read the promise with use.
First, a small data module. The delay stands in for a slow database or API so you can see the streaming behavior:
// lib/messages.js
export async function getMessage() {
await new Promise((resolve) => setTimeout(resolve, 2000));
return 'Your order has shipped.';
}Next, the Server Component. It creates the promise and passes it down:
// app/page.jsx (a Server Component)
import { Suspense } from 'react';
import { getMessage } from '../lib/messages';
import { Message } from './Message';
export default function Page() {
const messagePromise = getMessage(); // started, not awaited
return (
<main>
<h1>Inbox</h1>
<Suspense fallback={<p>Waiting for message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
</main>
);
}Page is no longer async. It returns immediately, because it never waits for anything. The request for the message starts as soon as getMessage() is called, so the work is already running while React renders the rest of the tree.
Finally, the Client Component:
// app/Message.jsx
'use client';
import { use } from 'react';
export function Message({ messagePromise }) {
const message = use(messagePromise);
return <p>Here is the message: {message}</p>;
}The user sees the <h1> and the fallback text immediately. About two seconds later, the fallback is replaced by the message. The page did not wait for the data before showing the parts that don't need it.
The fetch in your own app will usually call a database client or an absolute URL. A relative URL such as /api/message has no origin on the server. The fetch in a Server Component cannot resolve it, so use a full URL or call the data layer directly.
What travels over the network
The promise is not sent as an object. Promises cannot be copied between machines. React uses its server rendering protocol to describe the promise instead.
- The server renders
Pageand sees a promise in the props forMessage. It writes a placeholder for that promise into the output stream and keeps the connection open. - The browser receives the HTML and the stream so far. On the client, React builds a promise from the placeholder. That promise is still pending.
Messagecallsuseon it. The promise is pending, soMessagesuspends and theSuspensefallback stays on screen.- When the server promise settles, the server writes the result into the same stream. React on the client settles its promise and retries rendering
Message.
A consequence follows from this design: the value a promise resolves to must be something React can serialize. Strings, numbers, booleans, arrays, plain objects, Date objects, Map, Set, and other promises all work. Functions, class instances, and symbols that are not registered do not. If you resolve with a database row that holds a class instance, convert it to a plain object before it leaves the server.
Why this promise is safe to read with `use`
In an earlier chapter you saw that a promise created during the render of a Client Component is a problem. A new promise is made on every render, and use would suspend on a new pending promise each time. Rendering never finishes.
A promise that comes from a Server Component does not have this problem. The server creates it once for that render of the page. On the client, React turns it into one promise object and passes it into Message as a prop. When Message re-renders because of its own state or a parent update, the prop is the same promise. use reads a settled promise's value without suspending again.
The rule to remember is that identity is stable when the promise is created outside the Client Component's render. A Server Component is one such place. A module-level cache or a parent that keeps the promise in state are others.
A server render does repeat the call. Each new request to the page runs Page again and starts a new getMessage(). If a framework refreshes the route and re-renders the Server Component, the new render produces a new promise, and Message suspends again until the new one settles. This matches what you want: fresh data, with a fallback while it loads.
Starting several requests in parallel
Passing promises makes it easy to run requests at the same time. Start them all before anything waits:
// app/page.jsx (a Server Component)
import { Suspense } from 'react';
import { getMessage, getNotifications } from '../lib/messages';
import { Message } from './Message';
import { Notifications } from './Notifications';
export default function Page() {
const messagePromise = getMessage();
const notificationsPromise = getNotifications();
return (
<main>
<h1>Inbox</h1>
<Suspense fallback={<p>Waiting for message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
<Suspense fallback={<p>Loading notifications...</p>}>
<Notifications notificationsPromise={notificationsPromise} />
</Suspense>
</main>
);
}Both requests start at once. Each part appears when its own data arrives, because each has its own Suspense boundary. If you put both components in one boundary, the fallback stays until both promises settle.
Compare this with awaiting in sequence:
// Slower: the second request does not start until the first finishes.
const message = await getMessage();
const notifications = await getNotifications();This pattern is called a waterfall. Total time is the sum of both requests instead of the longer of the two. If the requests do not depend on each other, start them together.
If two components need the same data in one render, call a function wrapped with cache from React in both places. In Server Components, cache returns the same result for the same arguments during one request, so the work happens once. The promise you pass to different components is then the same promise.
// lib/messages.js
import { cache } from 'react';
export const getMessage = cache(async () => {
await new Promise((resolve) => setTimeout(resolve, 2000));
return 'Your order has shipped.';
});When the server promise rejects
A rejected promise behaves the same way it does in a Client Component. use throws the rejection during render, and the nearest error boundary shows its fallback. Two details are specific to the server case.
First, error boundaries must be Client Components, because they rely on class component lifecycle features. Wrap the library's boundary in a small client file so you can use it from a Server Component:
// app/MessageBoundary.jsx
'use client';
import { ErrorBoundary } from 'react-error-boundary';
export function MessageBoundary({ children }) {
return (
<ErrorBoundary fallback={<p>Could not load the message.</p>}>
{children}
</ErrorBoundary>
);
}Use it in the page, outside the Suspense boundary:
// app/page.jsx (a Server Component)
import { Suspense } from 'react';
import { getMessage } from '../lib/messages';
import { Message } from './Message';
import { MessageBoundary } from './MessageBoundary';
export default function Page() {
const messagePromise = getMessage();
return (
<main>
<h1>Inbox</h1>
<MessageBoundary>
<Suspense fallback={<p>Waiting for message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
</MessageBoundary>
</main>
);
}Second, in production builds React does not send the original error message from the server to the browser, because it might contain private details. The client receives a generic error with a digest, a short identifier that you can match against your server logs. In development you see the full message. Plan for this: your fallback UI should not depend on the text of the error.
You can also catch the error on the server and return a fallback value, as you did in the earlier chapter:
const messagePromise = getMessage().catch(() => 'No message found.');This gives the Client Component a promise that always resolves. Choose a fallback value when the page can still make sense without the real data. Choose an error boundary when the user should know something went wrong.
Server `await` versus a passed promise
Both approaches stream the page. They differ in where the waiting happens and who needs the data.
| Question | `await` in a Server Component | Promise passed to a Client Component |
|---|---|---|
| Where is the value read? | On the server, before the component returns | In the browser, with `use` |
| Does the component need `async`? | Yes | No |
| What blocks while data loads? | The component and, without a boundary, its siblings | Only the Client Component that calls `use` |
| Can the reader use state and effects? | No, Server Components cannot | Yes, it is a Client Component |
| Shipped to the browser as | Rendered output only | Rendered output plus the Client Component's code |
The last row matters. A Client Component adds JavaScript to the bundle. If the component only displays the value and has no interactivity, an async Server Component inside Suspense keeps that code on the server. Reach for a passed promise when the consumer needs client features, such as local state, event handlers, or browser APIs. The final chapter returns to this decision.
use can also be called in a Server Component, but React recommends async and await there. With await, rendering resumes where it stopped. With use, React re-renders the component after the data resolves.
Common mistakes
- Awaiting the promise before passing it.
<Message messagePromise={await getMessage()} />passes a string, not a promise. The page blocks again andusewill fail on a non-promise value. - Forgetting
'use client'.useitself works in Server Components, but the pattern in this chapter depends on the reader being a Client Component. Without the directive, React treats the file as a Server Component. - Resolving with a non-serializable value. A function or class instance in the resolved value causes an error when the server tries to send it.
- Missing
Suspense. Without a boundary aboveMessage, the suspension reaches the nearest boundary higher up, or the framework's loading state. A larger part of the page then shows a fallback than you intended. - Putting the error boundary inside the
Suspense. A boundary placed below the component that callsusecannot catch what that component throws. Place the error boundary above the component that reads the promise. - Creating the promise in a Client Component's render. This is the unstable-identity bug from earlier in the tutorial. Move creation to the Server Component.
Exercise
A Server Component runs const message = await getMessage(); and then renders <Message message={message} />. A teammate says to change it to <Message messagePromise={getMessage()} /> with use inside Message. What is the benefit, and what must be true of Message for the change to work?
Show answer
The benefit is that the Server Component no longer waits for the data. It returns right away, the rest of the page streams to the browser, and the nearest Suspense boundary shows a fallback until the promise resolves. For this to work, Message must be a Client Component (marked with 'use client') that calls use(messagePromise), it must be wrapped in a Suspense boundary, and the promise must resolve to a serializable value. If Message has no state or event handlers, an async Server Component inside Suspense would also work and would keep its code off the client.
Exercise
The page below should show data from two independent requests, but it takes as long as both requests added together. Why, and how do you fix it? const a = await getA(); const b = await getB(); return <Panel a={a} b={b} />;
Show answer
The second await does not run until the first request finishes, which creates a waterfall. To fix it, start both calls before waiting: const aPromise = getA(); const bPromise = getB();. Then pass each promise to a Client Component that reads it with use, each inside its own Suspense boundary. Alternatively, use await Promise.all([getA(), getB()]) if the page should wait for both before rendering.
Exercise
In production, your error boundary fallback tries to show error.message from a rejected server promise, but users see a generic message. Why does this happen, and where do you find the real cause?
Show answer
React removes the original error message from server errors in production builds so private details do not reach the browser. The client gets a generic error with a digest. Use the digest to find the matching entry in your server logs, where the full error is recorded. The fallback UI should use text that you wrote, not the error's message.