0
0
NextJSframework~5 mins

Streaming and partial rendering in NextJS

Choose your learning style9 modes available
Introduction

Streaming and partial rendering let your web page show parts of content as soon as they are ready. This makes the page feel faster and smoother for users.

When loading a page with lots of data that takes time to fetch.
When you want to show a header or navigation quickly before the main content loads.
When parts of the page depend on different data sources that load at different speeds.
When you want to improve user experience by showing content progressively.
When building pages with server components that fetch data asynchronously.
Syntax
NextJS
export default async function Page() {
  const data = await fetchData();
  return (
    <>
      <Header />
      <MainContent data={data} />
      <Footer />
    </>
  );
}
Use async functions in server components to fetch data before rendering.
Next.js automatically streams the HTML to the browser as parts become ready.
Examples
This example fetches user data first and streams the profile. Comments can load separately.
NextJS
export default async function Page() {
  const user = await fetchUser();
  return (
    <>
      <UserProfile user={user} />
      <Comments />
    </>
  );
}
Using Suspense lets you show a loading state while MainContent loads.
NextJS
import React, { Suspense } from 'react';

export default function Page() {
  return (
    <>
      <Header />
      <Suspense fallback={<Loading />}> 
        <MainContent />
      </Suspense>
    </>
  );
}
Sample Program

This Next.js component shows a heading immediately. The main content waits 2 seconds to fetch data, showing a loading message meanwhile. Once data arrives, it replaces the loading message.

NextJS
import React, { Suspense } from 'react';

async function fetchData() {
  return new Promise(resolve => setTimeout(() => resolve('Hello from server!'), 2000));
}

function Loading() {
  return <p>Loading content...</p>;
}

async function MainContent() {
  const message = await fetchData();
  return <p>{message}</p>;
}

export default function Page() {
  return (
    <main>
      <h1>Welcome to Streaming Demo</h1>
      <Suspense fallback={<Loading />}>
        <MainContent />
      </Suspense>
    </main>
  );
}
OutputSuccess
Important Notes

Streaming improves user experience by showing parts of the page early.

Use Suspense to handle loading states gracefully.

Server components in Next.js support async data fetching and streaming by default.

Summary

Streaming sends page parts to the browser as soon as they are ready.

Partial rendering lets you show loading states for slow parts.

Next.js makes streaming easy with async server components and Suspense.