X

Static Rendering in Next.js

This improves performance by serving pre-built HTML files to clients instead of dynamically generating them for each user request.

Static rendering in Next.js refers to the process of pre-rendering pages at build time instead of on each request. This improves performance by serving pre-built HTML files to clients instead of dynamically generating them for each user request.

Next.js provides several methods for static rendering:

1. Static Generation (SG): This is the default behaviour in Next.js. Pages that use Static Generation are generated at build time and reused on each request. This is suitable for pages with content that doesn't change frequently.

2. Incremental Static Regeneration (ISR): This feature allows you to update static pages at runtime without rebuilding the entire site. With ISR, you can specify how frequently the page should be re-rendered, and Next.js will regenerate the page in the background when a request is made after that interval has passed. ISR is useful for pages with dynamic content that needs to be updated frequently.

To use static rendering in Next.js, you typically define a getStaticProps function in your page components to fetch data at build time and return it as props to the component. Here's an example:
// pages/index.js

import React from 'react';

export default function Home({ data }) {
  return (
    <div>
      <h1>Static Rendering in Next.js</h1>
      <p>{data.message}</p>
    </div>
  );
}

export async function getStaticProps() {
  // Fetch data from an API or other source
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();

  // Pass data to the page component as props
  return {
    props: {
      data,
    },
  };
}

In this example, the `getStaticProps` function fetches data from an API at build time and passes it as props to the `Home` component. The Home component will then be pre-rendered with this data when the site is built.

To enable Incremental Static Regeneration, you can use the `revalidate` option in the `getStaticProps` function:

export async function getStaticProps() {
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();

  return {
    props: {
      data,
    },
    revalidate: 60, // Regenerate page every 60 seconds
  };
}

With this setup, Next.js will re-generate the page every 60 seconds, allowing you to serve updated content without rebuilding the entire site, how cool is that :)