Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readReact

Stream comments with React use()

Pass a promise from a Server Component and let a Suspense boundary handle the wait while the rest of the page renders.

Your post page has enough data to render its heading, but the comments are still loading. If the Server Component awaits the comments before returning the page, the heading has to wait too. Start the comments request on the server and let the comments panel read its promise.

Pass the promise across the boundary

Use this pair of components in an app that supports React Server Components. The page creates the promise and returns its heading without awaiting the comments. The timer stands in for a slow data source.

Try the example on a page that renders at request time. If your framework prerenders the page, the timer can finish before the first request and you may see the comment without the loading message.

// PostPage.jsx
import { Suspense } from 'react'
import Comments from './Comments.jsx'

async function getComments() {
  await new Promise((resolve) => setTimeout(resolve, 800))
  return ['I brought a spare map.']
}

export default function PostPage() {
  const commentsPromise = getComments()
  return (
    <article>
      <h1>Trail notes</h1>
      <Suspense fallback={<p>Loading comments…</p>}>
        <Comments commentsPromise={commentsPromise} />
      </Suspense>
    </article>
  )
}

The heading can render with Loading comments… in the comments slot while the promise is pending.

// Comments.jsx
'use client'

import { use } from 'react'

export default function Comments({ commentsPromise }) {
  const comments = use(commentsPromise)
  return <p>{comments.join(' · ')}</p>
}

After the promise resolves, the comments panel reads the string and displays I brought a spare map.

diagram

One slot waits for comments

The heading stays in place while the Suspense slot switches from its fallback to the comment.

React can stream the promise result because the promise crosses the boundary as a prop. Pass a promise that resolves to a serializable value, such as the array of strings here. Start the fetch on the server so the Client Component can read the same promise across render retries.

Add an error boundary around the comments area if fetching can fail. The Suspense fallback covers the wait, and the error boundary supplies a failure message when the promise rejects. If comments are optional, the data function can catch the error and resolve to a fallback value instead.