ApiaryActive
Try: pause · settings · learn · wipe
← Community / Reading Room
NS
nextjs · 4 min read

nextjs streaming with suspense

=====================================================

=====================================================

As a developer, you're likely familiar with the concept of Server-Side Rendering (SSR) in Next.js. It allows you to pre-render pages on the server, which can improve performance and SEO. However, traditional SSR can have its limitations when dealing with complex or dynamic content. That's where Next.js Streaming with Suspense comes into play.

What is Next.js Streaming?


Next.js Streaming is a feature that allows you to stream the rendering of a page from the server as it happens, rather than waiting for the entire page to be rendered at once. This can improve performance and provide a better user experience by reducing the initial load time.

Introducing Suspense


Suspense is a built-in React component that allows you to handle loading states and errors in a more elegant way. When used with Next.js Streaming, it enables you to create loading boundaries around sections of your page that need to be rendered dynamically.

The Magic Happens: loading.tsx


The key to making Suspense work with Next.js Streaming is the loading.tsx file. This file contains a React component that will be rendered when a section of the page is still loading. By default, Next.js provides a basic loading animation, but you can customize it to fit your needs.

Here's an example of a custom loading.tsx component:

import { Loading } from '@next/legacy';

const CustomLoading = () => {
  return (
    <div className="flex justify-center">
      <svg
        xmlns="http://www.w3.org/2000/svg"
        viewBox="0 0 100 80"
        fill="#333"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-miterlimit="10"
        stroke="#fff"
      >
        <rect x="10" y="20" width="30" height="40" rx="3" />
        <rect x="50" y="20" width="30" height="40" rx="3" />
      </svg>
    </div>
  );
};

export default CustomLoading;

Example 1: Partial Prerendering


One of the benefits of Next.js Streaming with Suspense is that you can partially prerender a page. This means that while the dynamic sections are still loading, the static parts of the page will be rendered first.

Here's an example of how to use loading.tsx in conjunction with partial prerendering:

import Head from 'next/head';
import CustomLoading from '../components/CustomLoading';

const HomePage = () => {
  return (
    <div>
      <Head>
        <title>Home Page</title>
      </Head>
      <h1>Welcome to our home page!</h1>
      <Suspense fallback={<CustomLoading />}>
        {/* Dynamic content goes here */}
        <p>This is some dynamic content.</p>
      </Suspense>
    </div>
  );
};

Example 2: Real-World Scenario


Let's say you're building a blog with Next.js, and each post has a comments section. You can use loading.tsx to create a loading boundary around the comments section while it's still rendering.

Here's an example of how to implement this:

import { useState } from 'react';
import CustomLoading from '../components/CustomLoading';

const PostPage = () => {
  const [comments, setComments] = useState([]);

  useEffect(() => {
    // Simulate API call to fetch comments
    const apiCall = async () => {
      const response = await fetch('/api/comments');
      const data = await response.json();
      setComments(data);
    };
    apiCall();
  }, []);

  return (
    <div>
      <h1>Post Title</h1>
      <p>Post content...</p>
      <Suspense fallback={<CustomLoading />}>
        {/* Comments section */}
        {comments.map((comment) => (
          <p key={comment.id}>{comment.text}</p>
        ))}
      </Suspense>
    </div>
  );
};

Example 3: API Integration


Next.js Streaming with Suspense can also be used to integrate with APIs. For example, let's say you're building a real-time chat application, and you want to display a list of online users.

Here's an example of how to use loading.tsx in conjunction with API integration:

import { useState } from 'react';
import CustomLoading from '../components/CustomLoading';

const ChatPage = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    // Simulate API call to fetch online users
    const apiCall = async () => {
      const response = await fetch('/api/users');
      const data = await response.json();
      setUsers(data);
    };
    apiCall();
  }, []);

  return (
    <div>
      <h1>Chat Page</h1>
      <p>Start typing to send a message...</p>
      <Suspense fallback={<CustomLoading />}>
        {/* Online users list */}
        {users.map((user) => (
          <p key={user.id}>{user.name}</p>
        ))}
      </Suspense>
    </div>
  );
};

When NOT to Use Next.js Streaming with Suspense


While Next.js Streaming with Suspense is a powerful feature, there are some scenarios where it may not be the best choice. For example:

  • If you have a very simple page structure and don't need to render dynamic content.
  • If you're dealing with extremely complex or large datasets that can cause performance issues.

Related Apiary Lessons


If you're new to Next.js Streaming with Suspense, here are some related lessons from the Apiary hive:

Conclusion


Next.js Streaming with Suspense is a powerful feature that can improve performance and provide a better user experience. By understanding how to use loading.tsx in conjunction with partial prerendering, real-world scenarios, and API integration, you can unlock the full potential of Next.js Streaming.

As we wrap up this lesson, remember: "The hive is always buzzing with new ideas – but only when they're properly rendered!"

Frequently asked
What is nextjs streaming with suspense about?
=====================================================
What is Next.js Streaming?
Next.js Streaming is a feature that allows you to stream the rendering of a page from the server as it happens, rather than waiting for the entire page to be rendered at once. This can improve performance and provide a better user experience by reducing the initial load time.
What should you know about introducing Suspense?
Suspense is a built-in React component that allows you to handle loading states and errors in a more elegant way. When used with Next.js Streaming, it enables you to create loading boundaries around sections of your page that need to be rendered dynamically.
What should you know about the Magic Happens: loading.tsx?
The key to making Suspense work with Next.js Streaming is the loading.tsx file. This file contains a React component that will be rendered when a section of the page is still loading. By default, Next.js provides a basic loading animation, but you can customize it to fit your needs.
What should you know about example 1: Partial Prerendering?
One of the benefits of Next.js Streaming with Suspense is that you can partially prerender a page. This means that while the dynamic sections are still loading, the static parts of the page will be rendered first.
References & sources
  1. Apiary Reading RoomOpen, cited knowledge base — funded to keep bee & practical research free.
From the Apiary Reading Room. Opinion & editorial — not financial advice. We don't overclaim.
More from the Reading Room