use·续2

button { margin-right: 10px; }

Streaming data from server to client

Data can be streamed from the server to the client by passing a Promise as a prop from a Server Component to a Client Component.

import { fetchMessage } from './lib.js';
import { Message } from './message.js';

export default function App() {
  const messagePromise = fetchMessage();
  return (
    <Suspense fallback={<p>waiting for message...</p>}>
      <Message messagePromise={messagePromise} />
    </Suspense>
  );
}

The Client Component then takes the Promise it received as a prop and passes it to the use API. This allows the Client Component to read the value from the Promise that was initially created by the Server Component.

// message.js
'use client';

import { use } from 'react';

export function Message({ messagePromise }) {
  const messageContent = use(messagePromise);
  return <p>Here is the message: {messageContent}</p>;
}

Because Message is wrapped in a Suspense boundary, the fallback will be displayed until the Promise is resolved. When the Promise is resolved, the value will be read by the use API and the Message component will replace the Suspense fallback.

```js src/message.js active "use client";

import { use, Suspense } from "react";

function Message({ messagePromise }) { const messageContent = use(messagePromise); return

Here is the message: {messageContent}

; }

export function MessageContainer({ messagePromise }) { return ( <Suspense fallback={

⌛Downloading message...

}> ); }


```js src/App.js hidden
import { useState } from "react";
import { MessageContainer } from "./message.js";

function fetchMessage() {
  return new Promise((resolve) => setTimeout(resolve, 1000, "⚛️"));
}

export default function App() {
  const [messagePromise, setMessagePromise] = useState(null);
  const [show, setShow] = useState(false);
  function download() {
    setMessagePromise(fetchMessage());
    setShow(true);
  }

if (show) {
    return <MessageContainer messagePromise={messagePromise} />;
  } else {
    return <button onClick={download}>Download message</button>;
  }
}

```js src/index.js hidden import React, { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import './styles.css';

// TODO: update this example to use // the Codesandbox Server Component // demo environment once it is created import App from './App';

const root = createRoot(document.getElementById('root')); root.render( );


> [!INFO]
>
> #### Should I resolve a Promise in a Server or Client Component? 
>
> If you have a Promise, at some point you need to unwrap it to read its value. You unwrap it with `await` in a Server Component, and with `use` in a Client Component.
>
> Usually, the simplest option is to `await` the Promise where you create it. The Server Component suspends until the data is ready, and everything below it waits too:
>
```js
// Server Component
export default async function App() {
  const messageContent = await fetchMessage();
  return <Message messageContent={messageContent} />;
}

However, you don't have to unwrap it right away. You can pass the Promise down as a prop, and unwrap it deeper in the tree. The component that reads the Promise still suspends, but only that part of the tree waits for the data. Wrap that component in a <Suspense> boundary to show a fallback while the rest of the page renders immediately.

For example, a deeper Server Component can await the Promise it receives:

import { Suspense } from 'react';

// Server Component
export default function App() {
  const messagePromise = fetchMessage();
  return (
    <Suspense fallback={<p>⌛Downloading message...</p>}>
      <Message messagePromise={messagePromise} />
    </Suspense>
  );
}

// Server Component
async function Message({ messagePromise }) {
  const messageContent = await messagePromise;
  return <p>{messageContent}</p>;
}

Or, in a separate file, a Client Component can unwrap the same Promise with use:

// Client Component
'use client';

import { use } from 'react';

export function Message({ messagePromise }) {
  const messageContent = use(messagePromise);
  return <p>{messageContent}</p>;
}

Passing the Promise down works the same way in both cases. Both suspend where the Promise is read, and both unblock the UI above. The only difference is that Client Components can't await during render, so they unwrap the Promise with use instead. A common case is interactive content like popovers and tooltips, where the data is only needed after a hover or click.

See Revealing content together at once for guidance on where to place Suspense boundaries.


Displaying an error with an Error Boundary

If the Promise passed to use is rejected, the error propagates to the nearest Error Boundary. Wrap the component that calls use in an Error Boundary to display a fallback when the Promise is rejected.

In the example below, fetchData rejects on the first attempt and succeeds on retry. The Error Boundary catches the rejection and shows a fallback with a "Try again" button.

```js src/App.js active import { use, Suspense, useState, startTransition } from "react"; import { ErrorBoundary } from "react-error-boundary"; import { fetchData, refetchData } from "./data.js";

export default function App() { const [albumsPromise, setAlbumsPromise] = useState( () => fetchData('/the-beatles/albums') );

function handleRetry() { startTransition(() => { setAlbumsPromise(refetchData('/the-beatles/albums')); }); }

return ( ( <>

⚠️ Something went wrong loading the albums.

</> )} > <Suspense fallback={

Loading...

}> ); }

function Albums({ albumsPromise }) { const albums = use(albumsPromise); return (

    {albums.map(album => (
  • {album.title} ({album.year})
  • ))}
); }


```js src/data.js hidden
// Note: the way you would do data fetching depends on
// the framework that you use together with Suspense.
// Normally, the caching logic would be inside a framework.

let cache = new Map();
let retried = false;

export function fetchData(url) {
  if (!cache.has(url)) {
    cache.set(url, getData(url));
  }
  return cache.get(url);
}

export function refetchData(url) {
  cache.delete(url);
  retried = true;
  return fetchData(url);
}

async function getData(url) {
  // Add a fake delay to make the loading state visible.
  await new Promise(resolve => setTimeout(resolve, 1000));
  if (url === '/the-beatles/albums') {
    // Fail the first attempt to demonstrate the Error Boundary,
    // then succeed on retry.
    if (!retried) {
      throw new Error('Example Error: Failed to fetch albums');
    }
    return [{
      id: 13,
      title: 'Let It Be',
      year: 1970
    }, {
      id: 12,
      title: 'Abbey Road',
      year: 1969
    }, {
      id: 11,
      title: 'Yellow Submarine',
      year: 1969
    }, {
      id: 10,
      title: 'The Beatles',
      year: 1968
    }];
  }
  throw new Error('Not implemented');
}

```json package.json hidden { "dependencies": { "react": "19.0.0", "react-dom": "19.0.0", "react-scripts": "^5.0.0", "react-error-boundary": "4.0.3" }, "main": "/index.js" }


---

## Usage (Browser)

### Rendering a component only in the browser

Pass the value returned by [`browser`](/reference/react-dom/browser) to `use` inside a component that should only render in the browser.

Click **Reload** to see the loading fallback in the initial HTML. After hydration, React displays the draft loaded from `localStorage`.

```js src/App.js active
import { Suspense, use, useState } from 'react';
import { browser } from 'react-dom';

function SavedDraft() {
  use(browser('The draft is stored in localStorage.'));
  const [draft, setDraft] = useState(
    () => localStorage.getItem('draft') ?? ''
  );

function handleChange(event) {
    const nextDraft = event.target.value;
    setDraft(nextDraft);
    localStorage.setItem('draft', nextDraft);
  }

return (
    <label>
      Draft:
      <textarea
        value={draft}
        onChange={handleChange}
        rows={4}
        cols={30}
      />
    </label>
  );
}

export default function App() {
  return (
    <>
      <h1>Saved draft</h1>
      <Suspense fallback={<p>Loading draft...</p>}>
        <SavedDraft />
      </Suspense>
    </>
  );
}

```js src/Document.js hidden import App from './App.js';

export default function Document() { return ( Saved draft ); }


```js src/index.js hidden
import { hydrateRoot } from 'react-dom/client';
import { renderToReadableStream } from 'react-dom/server';
import Document from './Document.js';
import { flushReadableStreamToFrame } from './demo-helpers.js';
import './styles.css';

async function main(frame) {
  const stream = await renderToReadableStream(<Document />);
  await flushReadableStreamToFrame(stream, frame);

// Wait so both the fallback and hydrated content are visible.
  await new Promise(resolve => setTimeout(resolve, 1200));
  hydrateRoot(frame.contentDocument, <Document />);
}

main(document.getElementById('preview'));

```js src/demo-helpers.js hidden export async function flushReadableStreamToFrame(readable, frame) { const doc = frame.contentWindow.document; const decoder = new TextDecoder(); const reader = readable.getReader();

while (true) { const {done, value} = await reader.read(); if (done) { break; } doc.write(decoder.decode(value, {stream: true})); }

doc.write(decoder.decode()); doc.close(); }


```html public/index.html hidden
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Browser-only rendering</title>
</head>
<body>
  <iframe id="preview" title="Rendered page"></iframe>
</body>
</html>

```css src/styles.css hidden iframe { width: 100%; height: 160px; border: 0; }


```json package.json hidden
{
  "dependencies": {
    "react": "19.3.0-canary-f1f7ed2a-20260904",
    "react-dom": "19.3.0-canary-f1f7ed2a-20260904",
    "react-scripts": "latest"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

During server rendering, use(browser()) suspends the component and React includes the closest Suspense boundary's fallback in the HTML. In the browser, use(browser()) returns undefined and the saved draft renders normally.


Troubleshooting

I'm getting an error: "Suspense Exception: This is not a real error!"

You are calling use inside a try-catch block. use throws internally to integrate with Suspense, so it cannot be wrapped in try-catch. Instead, wrap the component that calls use in an Error Boundary to handle errors.

function Albums({ albumsPromise }) {
  try {
    // ❌ Don't wrap `use` in try-catch
    const albums = use(albumsPromise);
  } catch (e) {
    return <p>Error</p>;
  }
  // ...

Instead, wrap the component in an Error Boundary:

function Albums({ albumsPromise }) {
  // ✅ Call `use` without try-catch
  const albums = use(albumsPromise);
  // ...
// ✅ Use an Error Boundary to handle errors
<ErrorBoundary fallback={<p>Error</p>}>
  <Albums albumsPromise={albumsPromise} />
</ErrorBoundary>

I'm getting a warning: "A component was suspended by an uncached promise"

The Promise passed to use is not cached, so React cannot reuse it across re-renders.

This commonly happens when calling fetch or an async function directly in render:

function Albums() {
  // 🔴 This creates a new Promise on every render
  const albums = use(fetch('/albums'));
  // ...
}

To fix this, cache the Promise so the same instance is reused:

// ✅ fetchData returns the same Promise for the same URL
const albums = use(fetchData('/albums'));

See caching Promises for Client Components for more details.


Sitemap

Overview of all docs pages