Sub topic 8
Streaming data from a Server Component to a Client Component
This chapter assumes you know function components and props, useState and useContext, JavaScript promises, and what a Suspense boundary does. It also assumes you have read how use unwraps a promise in a Client Component. Here you apply that to a framework that supports React Server Components, such as Next.js with the App Router.
The problem: awaiting blocks the page
An async Server Component can await data directly. That is simple, but the component renders nothing until the data arrives. If the data is slow and not needed for the first paint, everything below that component waits too.
You can avoid this by starting the request on the server and not awaiting it. You pass the unresolved promise to a Client Component as a prop. The server sends the rest of the page right away. When the promise settles, React streams the result to the browser.
How the pieces fit
The Server Component creates the promise and passes it as a prop. The Client Component reads the promise with use. A Suspense boundary shows a fallback until the value arrives.
The Server Component
The server code creates the promise and passes it down:
import { Suspense } from 'react';
import { Message } from './Message';
async function fetchMessage() {
const response = await fetch('/api/message');
if (!response.ok) {
throw new Error('Request failed');
}
return response.text();
}
export default function App() {
const messagePromise = fetchMessage();
return (
<Suspense fallback={<p>Loading...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
);
}App is not async, and it never uses await on messagePromise. Calling fetchMessage() starts the work, and the returned promise is handed to Message.
This is a sketch. On the server, fetch cannot resolve a relative URL like /api/message in every setup. Use an absolute URL or a data-access function, depending on your framework.
The Client Component
The component that reads the promise must be a Client Component. Mark it with the 'use client' directive at the top of its file:
'use client';
import { use } from 'react';
export function Message({ messagePromise }) {
const message = use(messagePromise);
return <p>Here is the message: {message}</p>;
}React suspends Message while the promise is pending. The nearest Suspense boundary above it, which is the one in App, shows Loading.... When the promise resolves, React replaces the fallback with the rendered paragraph.
Why this promise is safe
In an earlier chapter you saw that creating a promise during render in a Client Component causes trouble. Each re-render creates a new promise, and use suspends again on it. A promise created in a Server Component does not have this problem, because the server renders once per request. The promise is created once and React tracks it across the boundary. The Client Component receives the same promise on every render.
If you need a promise inside a Client Component, create it outside render or in a cache, as covered in the previous chapter. For data that the server can fetch, passing a promise from the server is the simpler route.
Handling failures
A rejected promise behaves the same as in the client-only case. use throws the rejection during render, and the nearest error boundary renders its fallback. Wrap the Suspense boundary in an error boundary:
import { Suspense } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import { Message } from './Message';
export function MessageContainer({ messagePromise }) {
return (
<ErrorBoundary fallback={<p>Could not load the message.</p>}>
<Suspense fallback={<p>Waiting for message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
</ErrorBoundary>
);
}Error boundaries are Client Components, so this container needs 'use client' at the top of its file. In that case it receives the promise from a Server Component parent.
Alternatively, attach .catch on the server so the promise always resolves to a fallback value:
const messagePromise = fetchMessage().catch(() => 'No message found.');Do not wrap use in try/catch. use is not supported inside a try/catch block.
What can cross the boundary
Props passed from a Server Component to a Client Component must be serializable. Promises are supported, but the value they resolve to must also be serializable. Plain objects, arrays, strings, numbers, and dates work. Functions and class instances do not.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Using `await` on the promise in the Server Component | The page waits for the data, so nothing streams | Pass the promise without awaiting it |
| Missing `'use client'` in the file that calls `use` on a promise from a Server Component | The component runs on the server, where you should use `await` instead | Add the directive, or switch to `async`/`await` there |
| No Suspense boundary above the reader | The nearest boundary is far up the tree, so a large part of the page shows a fallback | Place a boundary close to the component |
| No error boundary | A rejection reaches a higher boundary or breaks the page | Add an error boundary or a `.catch` fallback |
When to choose this pattern
Use it when the data is not needed for the first paint and the rest of the page can render without it. If the component needs the data to render anything useful, await in an async Server Component is simpler. If the component is a Client Component that only needs a value from context, use(Context) or useContext is enough. The final chapter compares these choices.
Exercise
A Server Component calls const data = await fetchData(); and then renders <Chart dataPromise={data} />, where Chart calls use(dataPromise). What is wrong, and how do you fix it so the page streams?
Show answer
The await resolves the promise before it is passed, so the server blocks on the fetch and use has nothing to wait for. Remove await so the Server Component passes the pending promise (const dataPromise = fetchData();). Wrap Chart in a Suspense boundary so a fallback shows until the data arrives.
Exercise
You want the client to show the text "No message found." instead of an error screen when the request fails. Where do you put the handling, and why not use try/catch around use?
Show answer
Attach .catch(() => 'No message found.') to the promise before passing it to the Client Component, so it always resolves. You can also wrap the Suspense boundary in an error boundary. try/catch around use is not supported.