avatarFardaKarimov

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4409

Abstract

e pre-rendered HTML pages can be directly served to the client without any additional processing on the server.</p><h2 id="6cac">How SSG Works:</h2><ol><li>During the build process, Next.js pre-renders all the pages specified for Static Site Generation.</li><li>The pre-rendered HTML pages are then stored in a cache and served directly to the client on subsequent requests.</li><li>If data changes or revalidation is required, the pages can be regenerated at build time or on a defined schedule.</li></ol><h2 id="795d">Example:</h2><p id="c2dc">Continuing from the previous example, let’s modify the Next.js application to use Static Site Generation for the items list.</p><div id="04e2"><pre>// pages/items.js</pre></div><div id="7b96"><pre><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;</pre></div><div id="8013"><pre>const Items = ({ items }) => { <span class="hljs-keyword">return</span> ( <span class="language-xml"><span class="hljs-tag"><<span class="hljs-name">ul</span>></span> </span><span class="language-xquery">{items.<span class="hljs-keyword">map</span>(<span class="hljs-type">item</span> => ( <li<span class="hljs-built_in"> key</span>={<span class="hljs-type">item</span><span class="hljs-built_in">.id</span>}</span><span class="language-xml">></span><span class="language-xquery">{<span class="hljs-type">item</span><span class="hljs-built_in">.name</span>}</span><span class="language-xml"><span class="hljs-tag"></<span class="hljs-name">li</span>></span></span> ))} </ul> ); };</pre></div><div id="082e"><pre><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getStaticProps</span>(<span class="hljs-params"></span>) { <span class="hljs-comment">// Fetch data from an API or database</span> <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(<span class="hljs-string">'https://example-api.com/items'</span>); <span class="hljs-keyword">const</span> items = <span class="hljs-keyword">await</span> res.<span class="hljs-title function_">json</span>();</pre></div><div id="bd00"><pre> <span class="hljs-keyword">return</span> { <span class="hljs-title"> props:</span> { <span class="hljs-built_in"> items,</span> }, }<span class="hljs-comment">;</span> }</pre></div><div id="d3ae"><pre><span class="hljs-built_in">export</span><span class="hljs-built_in"> default </span>Items;</pre></div><p id="d5e9">In this example, we replaced <code>getServerSideProps</code> with <code>getStaticProps</code>. Now, during the build process, Next.js will fetch the data from the API and pre-render the <code>Items</code> page with the fetched data. The pre-rendered HTML page will be served to the client on every request, resulting in faster page loads.</p><h1 id="5069">3. Incremental Static Regeneration (ISR)</h1><p id="f754">Incremental Static Regeneration is a feature of Next.js that allows you to update pre-rendered pages with new data, without the need to rebuild the entire application. It provides a balance between static generation and dynamic rendering, allowing developers to specify a revalidation interval to update the data on a defined schedule.</p><h2 id="ddc9">How ISR Works:</h2><ol><li>During the build process, Next.js pre-renders the pages specified for Incremental Static Regeneration, similar to SSG.</li><li>Instead of relying solely on build-time data, ISR allows you to define a revalidation interval (in seconds).</li><li>After the initial request, subsequent users will receive the pre-rendered page from the cache. However, in the background, Next.js will check if the revalidation interval has passed.</li><li>If the interval has passed, Next.js will fetch new data, re-render the page, and update the cache. This updated data will be served to future users, ensuring the page stays up-to-date without requiring a full rebuild.</li></ol><h2 id="1f9e">Example:</h2><p id="189a">Let’s extend the previous example and add Incremental Static Regeneration to update the items list on a regular basis.</p><div id="06ab"><pre>// pages/items.js</pre></div><div id="36d0"><pre><span class="hljs-keyword">import</span> Re

Options

act <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;</pre></div><div id="f566"><pre>const Items = ({ items }) => { <span class="hljs-keyword">return</span> ( <span class="language-xml"><span class="hljs-tag"><<span class="hljs-name">ul</span>></span> </span><span class="language-xquery">{items.<span class="hljs-keyword">map</span>(<span class="hljs-type">item</span> => ( <li<span class="hljs-built_in"> key</span>={<span class="hljs-type">item</span><span class="hljs-built_in">.id</span>}</span><span class="language-xml">></span><span class="language-xquery">{<span class="hljs-type">item</span><span class="hljs-built_in">.name</span>}</span><span class="language-xml"><span class="hljs-tag"></<span class="hljs-name">li</span>></span></span> ))} </ul> ); };</pre></div><div id="45d2"><pre><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getStaticProps</span>(<span class="hljs-params"></span>) { <span class="hljs-comment">// Fetch data from an API or database</span> <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(<span class="hljs-string">'https://example-api.com/items'</span>); <span class="hljs-keyword">const</span> items = <span class="hljs-keyword">await</span> res.<span class="hljs-title function_">json</span>();</pre></div><div id="c3d7"><pre> <span class="hljs-title class_">return</span> <span class="hljs-punctuation">{</span> <span class="hljs-symbol"> props:</span> <span class="hljs-punctuation">{</span> items, <span class="hljs-punctuation">}</span>, <span class="hljs-symbol"> revalidate:</span> <span class="hljs-number">3600</span>, <span class="hljs-comment">// Revalidate and update data every hour (in seconds)</span> <span class="hljs-punctuation">};</span> <span class="hljs-punctuation">}</span></pre></div><div id="f07c"><pre><span class="hljs-built_in">export</span><span class="hljs-built_in"> default </span>Items;</pre></div><p id="e193">In this example, we added the <code>revalidate</code> property to <code>getStaticProps</code>, setting it to 3600 seconds (1 hour). After the initial request, if one hour has passed, Next.js will fetch new data and update the items list without requiring a full rebuild. This way, users will see up-to-date content on subsequent visits while still benefiting from the performance gains of pre-rendering.</p><h1 id="d4d2">Conclusion</h1><p id="5df4">In conclusion, Next.js offers powerful rendering options to suit various use cases and performance requirements. Understanding the differences between Server-Side Rendering (SSR), Static Site Generation (SSG), and Incremental Static Regeneration (ISR) is essential for making informed decisions about how to build and optimize your Next.js applications.</p><ul><li>Use SSR when you need to generate HTML on each request and require real-time data fetching and rendering.</li><li>Use SSG for static content that doesn’t change frequently, as it provides better performance with pre-rendered HTML pages.</li><li>Use ISR when you want to combine the benefits of SSG with the ability to update data at regular intervals without rebuilding the entire application.</li></ul><p id="12b5">By leveraging these Next.js features effectively, you can create blazing-fast and highly efficient web applications, delivering a superior user experience to your audience.</p><h1 id="9f9e">In Plain English</h1><p id="8095"><i>Thank you for being a part of our community! Before you go:</i></p><ul><li><i>Be sure to <b>clap</b> and <b>follow</b> the writer! 👏</i></li><li><i>You can find even more content at <a href="https://plainenglish.io/"><b>PlainEnglish.io</b></a><b> 🚀</b></i></li><li><i>Sign up for our <a href="http://newsletter.plainenglish.io/"><b>free weekly newsletter</b></a>. 🗞️</i></li><li><i>Follow us on <a href="https://twitter.com/inPlainEngHQ"><b>Twitter</b></a></i>, <a href="https://www.linkedin.com/company/inplainenglish/"><b><i>LinkedIn</i></b></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><b><i>YouTube</i></b></a>, and <a href="https://discord.gg/GtDtUAvyhW"><b><i>Discord</i></b></a><b><i>.</i></b></li></ul></article></body>

Understanding the Differences Between SSR, SSG, and ISR in Next.js

Introduction

Next.js is a popular framework for building React applications, providing developers with a powerful set of features to enhance the performance and user experience of their web applications. Three of the essential concepts in Next.js are Server-Side Rendering (SSR), Static Site Generation (SSG), and Incremental Static Regeneration (ISR). In this article, we will delve into these concepts, understand their differences, and provide easy-to-follow examples to illustrate each one.

1. Server-Side Rendering (SSR)

Server-Side Rendering is a technique that allows generating HTML content on the server and sending a fully rendered page to the client. This means that when a user requests a page, the server processes the request, fetches the necessary data, and renders the page before sending it to the client’s browser.

How SSR Works:

  1. The client sends a request to the server for a specific page.
  2. The server receives the request and executes the appropriate code to generate the HTML content of the requested page, which may include fetching data from APIs or databases.
  3. The server then sends the fully rendered HTML page as a response to the client.
  4. The client’s browser receives the HTML and displays the page to the user.

Example:

Consider a basic Next.js application with a simple component that displays a list of items fetched from an API. With SSR, the list would be pre-rendered on the server before being sent to the client.

// pages/items.js
import React from 'react';
const Items = ({ items }) => {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
};
export async function getServerSideProps() {
  // Fetch data from an API or database
  const res = await fetch('https://example-api.com/items');
  const items = await res.json();
  return {
    props: {
      items,
    },
  };
}
export default Items;

In this example, the getServerSideProps function runs on the server during the initial request, fetching the data and passing it as a prop to the Items component. The server then renders the component with the data and sends the fully-rendered page to the client.

2. Static Site Generation (SSG)

Static Site Generation is a technique that generates HTML pages at build time instead of generating them on each request. This results in faster loading times and improved performance as the pre-rendered HTML pages can be directly served to the client without any additional processing on the server.

How SSG Works:

  1. During the build process, Next.js pre-renders all the pages specified for Static Site Generation.
  2. The pre-rendered HTML pages are then stored in a cache and served directly to the client on subsequent requests.
  3. If data changes or revalidation is required, the pages can be regenerated at build time or on a defined schedule.

Example:

Continuing from the previous example, let’s modify the Next.js application to use Static Site Generation for the items list.

// pages/items.js
import React from 'react';
const Items = ({ items }) => {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
};
export async function getStaticProps() {
  // Fetch data from an API or database
  const res = await fetch('https://example-api.com/items');
  const items = await res.json();
  return {
    props: {
      items,
    },
  };
}
export default Items;

In this example, we replaced getServerSideProps with getStaticProps. Now, during the build process, Next.js will fetch the data from the API and pre-render the Items page with the fetched data. The pre-rendered HTML page will be served to the client on every request, resulting in faster page loads.

3. Incremental Static Regeneration (ISR)

Incremental Static Regeneration is a feature of Next.js that allows you to update pre-rendered pages with new data, without the need to rebuild the entire application. It provides a balance between static generation and dynamic rendering, allowing developers to specify a revalidation interval to update the data on a defined schedule.

How ISR Works:

  1. During the build process, Next.js pre-renders the pages specified for Incremental Static Regeneration, similar to SSG.
  2. Instead of relying solely on build-time data, ISR allows you to define a revalidation interval (in seconds).
  3. After the initial request, subsequent users will receive the pre-rendered page from the cache. However, in the background, Next.js will check if the revalidation interval has passed.
  4. If the interval has passed, Next.js will fetch new data, re-render the page, and update the cache. This updated data will be served to future users, ensuring the page stays up-to-date without requiring a full rebuild.

Example:

Let’s extend the previous example and add Incremental Static Regeneration to update the items list on a regular basis.

// pages/items.js
import React from 'react';
const Items = ({ items }) => {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
};
export async function getStaticProps() {
  // Fetch data from an API or database
  const res = await fetch('https://example-api.com/items');
  const items = await res.json();
  return {
    props: {
      items,
    },
    revalidate: 3600, // Revalidate and update data every hour (in seconds)
  };
}
export default Items;

In this example, we added the revalidate property to getStaticProps, setting it to 3600 seconds (1 hour). After the initial request, if one hour has passed, Next.js will fetch new data and update the items list without requiring a full rebuild. This way, users will see up-to-date content on subsequent visits while still benefiting from the performance gains of pre-rendering.

Conclusion

In conclusion, Next.js offers powerful rendering options to suit various use cases and performance requirements. Understanding the differences between Server-Side Rendering (SSR), Static Site Generation (SSG), and Incremental Static Regeneration (ISR) is essential for making informed decisions about how to build and optimize your Next.js applications.

  • Use SSR when you need to generate HTML on each request and require real-time data fetching and rendering.
  • Use SSG for static content that doesn’t change frequently, as it provides better performance with pre-rendered HTML pages.
  • Use ISR when you want to combine the benefits of SSG with the ability to update data at regular intervals without rebuilding the entire application.

By leveraging these Next.js features effectively, you can create blazing-fast and highly efficient web applications, delivering a superior user experience to your audience.

In Plain English

Thank you for being a part of our community! Before you go:

Web Development
Front End Development
Nextjs
JavaScript
Technology
Recommended from ReadMedium