Back to Top

Partial Rendering in NextJs.

Updated 30 May 2024

Partial Rendering is an experimental feature introduced in Next.js 14. it could help make your websites load even faster. This blog post will explore what it is, why it’s important, and how to implement it in your NextJs projects.

What is Partial Rendering?

Partial Rendering in Next.js is a powerful feature that allows you to optimize your web application’s performance by selectively rendering only the parts of a page that have changed since the last request.

This can significantly reduce the amount of data that must be transferred between the server and the client, resulting in faster load times and a better experience.

For Example: Imagine, you are serving a web page to a user. Instead of reloading the entire page every time there is s a change, It focuses only on updating the parts of the page that need to be changed. it’s like renovating your house one room at a time instead of rebuilding the entire structure.

Understand the Headless Architecture

Start your headless eCommerce
now.
Find out More

Why is Partial Rendering Important?

It offers several benefits for web developers :

  • Improved Performance: By only updating the parts of the page that have changed, It can lead to faster load times and smoother user interactions.
  • Reduced server load: Partial rendering reduces server load by sending only necessary data to the client, enabling the server to handle more requests concurrently.
  • Better User Experience: Faster load times and smoother interactions can improve overall user experience, increasing user satisfaction and retention.

Implementing Partial Rendering in NextJs

Before starting let’s set up the Next.js project with the App router:

Step 1. Set up the project with an App router.

You can follow the setup next js blog that covers all about the next js project setup.

After Creating a new project, you can see the final folder structure.

.
├── app/
│   ├── favicon.ico
│   ├── globals.css
|   ├── layout.tsx
│   └── page.tsx
├── public/
│   ├── next.svg
│   └── vercel.svg
├── next.config.mjs
├── postcss.config.mjs
├── package-lock.json
├── package.json
├── tailwind.config.ts
├── tsconfig.json
└── README.md

Step 2. Create the components file to mount partial rendering.

We’ll create the components folder in the app directory and the components files inside the app/components/…

Let’s look at the example below:

.
├── app/
│   ├── components
        ├── BlogPost.tsx
        ├── BlogSkeleton.tsx
        ├── Comments.tsx
        └── type.ts

Write the code for BlogPost.tsx file.

import { PostDataType } from "./type";

export default function Blogpost({ postData }: { postData: PostDataType }) {
  return (
    <div className="container w-full overflow-hidden rounded-xl bg-white shadow-md">
      <div className="p-8">
        <div className="text-sm font-semibold uppercase tracking-wide text-indigo-500">
          Name: {postData.name}
        </div>
        <div className="text-sm font-semibold uppercase tracking-wide text-indigo-500">
          Email: {postData.email}
        </div>
        <p className="mt-2 text-gray-500">{postData.body}</p>
      </div>
    </div>
  );
}

Write the code for BlogSkeleton.tsx file.

function BlogSkeleton() {
  return (
    <div className="w-full overflow-hidden rounded-xl bg-white shadow-md">
      <div className="p-8">
        {/* Skeleton for the title */}
        <div className="h-4 animate-pulse rounded bg-gray-300 text-sm uppercase tracking-wide"></div>

        {/* A little space between the title and body */}
        <div className="mt-2"></div>

        {/* Skeleton for the body */}
        <div className="mb-2 h-4 animate-pulse rounded bg-gray-300"></div>
        <div className="mb-2 h-4 animate-pulse rounded bg-gray-300"></div>
        <div className="mb-2 h-4 animate-pulse rounded bg-gray-300"></div>
      </div>
    </div>
  );
}

export default function CommentsSkeleton() {
  return (
    <div className="flex w-full flex-col gap-4">
      {[...Array(2)].map((_, idx) => (
        <BlogSkeleton key={idx} />
      ))}
    </div>
  );
}

It’s the main file to fetch the comments from placeholder API’s

Write the code for Comments.tsx file. Let’s look at the example below:

import Post from "./Blogpost";
import { PostDataType } from "./type";

function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export default async function Comments({ delay }: { delay: number }) {
  await sleep(delay);

  const commensts = await fetch(
    "https://jsonplaceholder.typicode.com/posts/1/comments"
  ).then((res) => res.json());

  return (
    <div className="flex flex-col gap-4">
      {commensts.map((post: PostDataType) => (
        <Post key={post.id} postData={post} />
      ))}
    </div>
  );
}

Step 3. Import the components on the page.tsx file in the app directory.

The page.tsx file should exist in the app folder. we will Modify the code for mount partial rendering ( streaming ) of the post comments.

Let’s look at the example below:

import { Suspense } from "react";
import CommentsSkeleton from "./components/BlogSkeleton";
import Comments from "./components/Comments";

export default function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-between py-4">
      <div className="container">
        <h1 className="px-2 py-4 text-2xl font-bold text-indigo-500">
          Post Comments.
        </h1>
        <Suspense fallback={<CommentsSkeleton />}>
          <Comments delay={5000} />
        </Suspense>
        <p className="container absolute bottom-0 py-4 text-center">
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis
          dolores tempora reiciendis, dicta alias fugiat iusto debitis fuga
          voluptatibus similique, modi corrupti incidunt ipsam fugit eum
          dolorem! Cupiditate, ex tenetur.
        </p>
      </div>
    </main>
  );
}

You can see the result on localhost.

Partial Rendering Skeleton output.

Completed the partial rendering and now mounted the components updating parts.

Start your Headless Development with Webkul.

Happy Coding!!

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home