0
0
NextJSframework~5 mins

Streaming with Suspense in NextJS

Choose your learning style9 modes available
Introduction

Streaming with Suspense lets your app show parts of the page as soon as they are ready. This makes your app feel faster and smoother.

When loading large pages with multiple data sources.
When you want to show a loading placeholder for slow parts.
When you want to improve user experience by showing content early.
When you use React Server Components and want partial rendering.
When you want to reduce the time users wait before seeing something.
Syntax
NextJS
import { Suspense } from 'react';

export default function Page() {
  return (
    <Suspense fallback={<Loading />}> 
      <SomeComponent />
    </Suspense>
  );
}

The Suspense component wraps parts that may load slowly.

The fallback prop shows a placeholder while loading.

Examples
This example shows a simple Suspense usage with a loading message.
NextJS
import { Suspense } from 'react';

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

function Data() {
  // Imagine this fetches data
  return <p>Data loaded!</p>;
}

export default function Page() {
  return (
    <Suspense fallback={<Loading />}>
      <Data />
    </Suspense>
  );
}
Here Suspense wraps user info to show a loading message while it loads.
NextJS
import { Suspense } from 'react';

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

function UserInfo() {
  // Simulate slow data
  return <p>User: Alice</p>;
}

export default function Profile() {
  return (
    <div>
      <h1>Profile</h1>
      <Suspense fallback={<Loading />}>
        <UserInfo />
      </Suspense>
    </div>
  );
}
Sample Program

This component shows a blog post with comments. The comments are wrapped in Suspense to show a loading message if they take time to load.

NextJS
import { Suspense } from 'react';

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

function Comments() {
  // Simulate slow loading with a delay
  const comments = ['Great post!', 'Thanks for sharing.', 'Nice article!'];
  return (
    <ul>
      {comments.map((comment, i) => (
        <li key={i}>{comment}</li>
      ))}
    </ul>
  );
}

export default function BlogPost() {
  return (
    <article>
      <h1>My Blog Post</h1>
      <p>This is the content of the blog post.</p>
      <Suspense fallback={<Loading />}>
        <Comments />
      </Suspense>
    </article>
  );
}
OutputSuccess
Important Notes

Suspense works best with components that fetch data or load slowly.

Use simple fallback UI to keep users informed during loading.

Streaming with Suspense improves perceived speed by showing content early.

Summary

Streaming with Suspense lets parts of your page load and show separately.

Wrap slow components in Suspense with a fallback UI.

This makes your app feel faster and more responsive.