Nextjs Fundamentals · Data Fetching

Reading a promise with `use`

`use(promise)` in a Client Component

Reading a promise with use

A Server Component can await a promise during render, but a Client Component cannot be async. To read data that starts on the server in the browser, React provides use.

Start the fetch in the Server Component and pass the promise itself — not the resolved value — to the Client Component as a prop:

// app/blog/page.tsx
export default function Page() {
  const posts = getPosts(); // no await
  return (
    <Suspense fallback={<div>Loading…</div>}>
      <Posts posts={posts} />
    </Suspense>
  );
}

Then read the promise inside the Client Component with use:

'use client';
import { use } from 'react';

export default function Posts({ posts }) {
  const allPosts = use(posts);
  return (
    <ul>
      {allPosts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}

use unwraps the promise, so the component suspends until it resolves. That is why the component is wrapped in <Suspense>: the fallback shows while the data streams in, then React renders the content.

Unlike a hook, use may be called conditionally, but it must still be called during render. This pattern is how the server starts the request and the client streams the result in.

You are about to answer a short quiz on use(promise) in a Client Component.

  1. A Client Component can read a promise passed from a Server Component with React's use API.
  2. To stream data to a Client Component, the Server Component passes the ___ rather than the resolved value.
  3. use unwraps a promise and suspends the component until it resolves.
  4. A Client Component that calls use(promise) should be wrapped in ___ to show a fallback while it streams.
  5. A Client Component can be an async function and await the promise directly.