Sikau

Next.js · Day 9 · about 30 min

Loading UI and streaming

Show the fast parts now and stream the slow parts.

Don't wait for the slowest query

If reviews take two seconds to load, the whole page shouldn't wait. With streaming, Next.js sends the page as soon as the fast parts are ready and fills in slow parts later — using <Suspense> or a loading.jsx file.

Suspense boundaries and loading.jsx

import { Suspense } from "react";
import { getSpecial, getReviews } from "@/lib/special";

async function Reviews() {
  const reviews = await getReviews();
  return <ul>{reviews.map((r) => <li key={r}>{r}</li>)}</ul>;
}

export default async function Page() {
  const special = await getSpecial();
  return (
    <>
      <h1>Today: {special.name}</h1>
      <Suspense fallback={<p>Loading reviews…</p>}>
        <Reviews />
      </Suspense>
    </>
  );
}
  • loading.jsx in a route folder wraps that route's page in Suspense automatically — instant loading screens on navigation.
  • Place boundaries around independent slow parts so each can appear as soon as it's ready.
  • With Cache Components, uncached data must be inside Suspense; cached data ("use cache") can be part of the instant static shell.

The rest of this lesson

  • How streaming worksexplain
  • Designing loading statesexplain
  • What appears first?predict
  • What the visitor seesorder
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 19 lessons of Next.js