Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 50 ยท Data Mode

Streaming Data with Await and Suspense

Return promises from React Router loaders, render them with Await and Suspense, handle failures with errorElement, and learn which data should be streamed.

A loader normally holds the whole page back until its data is ready. That is the right default: the page appears complete, with no spinners and no layout jumps. But sometimes one slow query ruins an otherwise fast page. The product name and price come back in 40 ms, the list of recommendations takes 2 seconds, and the user stares at the old page for all of it.

React Router lets a loader return a promise without awaiting it. The router finishes the navigation as soon as the awaited data is in, renders the page, and the part that is still loading shows a fallback until the promise settles. This is called streaming (or deferred) data. In this lesson you will return promises from loaders, render them with Await and Suspense, handle their failures, and decide which data deserves this treatment. You should know loaders and, ideally, how React's Suspense works from use and Suspense.

Awaited versus streamed

Compare two loaders for a product page. In the first, everything is awaited:

JSX
// blocking loader - React Router (read-only)
export async function loader({ params }) {
  const product = await getProduct(params.id);
  const reviews = await getReviews(params.id); // slow
  return { product, reviews };
}

Here the navigation takes time(product) + time(reviews). Even if you swap in Promise.all, it takes as long as the slowest query. Now the streamed version:

JSX
// streaming loader - React Router (read-only)
export async function loader({ params }) {
  const product = await getProduct(params.id); // critical: awaited
  const reviews = getReviews(params.id);       // not awaited: a promise
  return { product, reviews };
}

The only change is a missing await. The loader still returns an object, but reviews is now a pending promise. The router waits for the awaited part, completes the navigation and hands the component an object whose reviews field is a promise.

React Router v7 versus v6. Older versions required wrapping such data in a defer() helper. In v7 defer is gone: you simply return plain objects that contain promises. If you read older tutorials that call defer({ reviews }), drop the helper and return the object.

flowchart TD
    A["Navigation starts"] --> B["Loader awaits critical data<br/>(product)"]
    B --> C["Loader returns { product, reviews promise }"]
    C --> D["Router renders the page, navigation is idle"]
    D --> E["Suspense fallback shows where reviews go"]
    E --> F["Promise resolves"]
    F --> G["Await renders the reviews"]
    E --> H["Promise rejects"]
    H --> I["Await errorElement renders"]

The page appears after the critical data. Streamed parts fill in later, or show an error without taking the page down.

Rendering a promise: Await and Suspense

To show a promise, wrap Await in Suspense. Suspense supplies the fallback while the promise is pending. Await waits for the promise you pass as resolve and calls its children as a function with the resolved value:

JSX
// product.jsx - React Router (read-only)
import { Suspense } from 'react';
import { Await, useLoaderData } from 'react-router';

export default function Product() {
  const { product, reviews } = useLoaderData();

  return (
    <article>
      <h1>{product.name}</h1>
      <p>{product.price}</p>

      <h2>Reviews</h2>
      <Suspense fallback={<p>Loading reviews...</p>}>
        <Await resolve={reviews} errorElement={<p>Reviews are unavailable right now.</p>}>
          {(list) => (
            <ul>
              {list.map((review) => (
                <li key={review.id}>{review.text}</li>
              ))}
            </ul>
          )}
        </Await>
      </Suspense>
    </article>
  );
}

Three details are worth knowing:

  • Where you put Suspense decides the size of the hole. The fallback replaces everything inside the nearest Suspense, so keep it tight around the streamed part.
  • errorElement on Await handles rejection locally. Inside it (or inside the children) you can call useAsyncError() to read the error, and useAsyncValue() inside the children gives the resolved value if you prefer a component to a render function. Without an errorElement, a rejected promise bubbles to the route's error boundary (see Error Boundaries and Error Elements).
  • React 19 can do the same job with use(). const list = use(reviews) inside a component wrapped in Suspense suspends until the promise settles. Await adds the error handling and the render-function shape in one package.

Real library or stand-in? The code above is the real API. The live examples below use a small hand-written version: a loader-like function that returns an object with one awaited value and one promise, an Await built from React's use() plus an error boundary, and React's own Suspense. Suspense and use() are the real React; Await and the loader are stand-ins. The stand-in errorElement is a function that receives the error, where the real one is an element that calls useAsyncError().

Await, Suspense and a failing stream

Open the desk lamp: the name appears after 300 ms, the reviews area shows its fallback, and 1.2 seconds later the list replaces it. Open the office chair: the page is just as fast, and the same slow stream fails without breaking anything else. The heading and navigation stay, and only the reviews area shows the error. That containment is the second benefit of streaming, after speed.

What should you stream?

Streaming is a tool for non-critical, slow, below-the-fold data. Use this checklist:

Await it (critical) Stream it (deferred)
The data the page cannot make sense without Recommendations, reviews, activity feeds
Anything that sets the document title or meta tags Counts and badges
Data that decides a 404 or a redirect Heavy analytics or charts below the fold
Content search engines must see in the first response Personalized extras

Why the middle row matters: a loader that decides "this product does not exist" has to be awaited, because it must be able to throw a 404 (see 404 Pages and Catch-All Routes) before anything renders. A streamed promise cannot change the page's status after the response has started on a server-rendered app.

Streaming also has costs. A page with five spinners loading in random order feels worse than one that waits a bit longer and appears whole. Layout shift is another risk: give each fallback roughly the size of the final content (a skeleton) so the page does not jump when data arrives.

How the user experiences a client navigation

In a client-side data router the navigation behaves like this. The user clicks a link, navigation.state becomes "loading" (see Pending and Optimistic UI), the awaited part of the loader runs, the new route renders and navigation.state goes back to "idle". Streamed promises keep running after the navigation has finished, which is exactly why the next page can show a fallback instead of making the old one wait.

The next example removes the network and shows the arithmetic. Each part of a page has a delay. Choose which parts to stream and see when they become visible.

When does each part appear?

With nothing streamed, every part waits for the slowest query: 1500 ms. Stream the reviews and the page appears at 900 ms (the related items still gate it). Stream both and the page is there after only 200 ms, with the slow parts arriving at their own pace. The same model is why the real loader above awaits only the product.

Common mistakes

  • Awaiting inside the component instead. Writing await in a component is not possible; use Await or use().
  • A promise created during render. Create it in the loader (once per navigation). A promise created inside a component is new on every render and suspends forever.
  • No Suspense boundary. A suspended component with no boundary above it falls back to the closest boundary, which may be the whole app. Always pair Await with a nearby Suspense.
  • Streaming data that decides the page. If the title, a redirect or a 404 depends on it, await it.
  • Forgetting the failure path. Every streamed promise can reject: add an errorElement or rely on a route-level boundary.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In React Router v7, how does a loader stream a slow query?

    In v7 you return plain objects that contain promises. The old defer() helper from v6 is not needed any more.
  2. 2. Which component shows the fallback while a streamed promise is pending?

    Suspense owns the fallback. Await waits for the promise and renders its children, or its errorElement when the promise rejects.
  3. 3. A product page must return a 404 when the product does not exist. How should that lookup be loaded?

    Decisions about status codes, redirects and not-found pages need the data before rendering, so the loader must await it. Only non-critical extras should be streamed.
  4. 4. A streamed promise rejects and its Await has an errorElement. What does the user see?

    Await handles its own rejection, so the failure stays local to that part of the page. Without an errorElement the error would bubble to the route's boundary.

Summary

  • A loader streams data by returning a promise (not awaiting it) as part of its result; v7 needs no defer() helper.
  • The router finishes navigation after the awaited data, then the page renders and streamed values arrive later.
  • Show a promise with <Suspense fallback> around <Await resolve errorElement>; read errors with useAsyncError and values with useAsyncValue.
  • Await data that affects the title, redirects, 404s or crucial content, and stream slow extras such as reviews and recommendations.
  • Give fallbacks a stable size to avoid layout shift, and always plan for rejection.

Next: Revalidation and Caching