Evolution of data fetching: From Next.js 12 to 13/14

December 27, 2023 at 12:29:00, written by @vmmon.th0

Next.js
fetch
javascript
typescript

Next.js is a React framework enhancing web development with features like SSR and SSG, significantly improving SEO by ensuring content is crawler-friendly. It boasts performance optimizations such as automatic code splitting, lazy loading images, and link prefetching. The framework's versatility allows for hybrid applications, combining server-rendered and statically generated pages. Notably, Next.js simplifies backend development with built-in API route. This concept is quite new and we could start to classify Next.js as a fullstack framework.


This archive aims to show you, as mentioned in the title, the evolution of data fetching in Next.js from 12 to 13/14.

What is data fetching in this Context ?

Data fetching in Next.js allows you to render your content in different ways, depending on your application's use case. These include pre-rendering with Server-side Rendering or Static Generation, and updating or creating content at runtime with Incremental Static Regeneration.

Data fetching on Next.js 12

In Next.js 12 the /pages folder is the core of the application. Each JavaScript, TypeScript, JSX, or TSX file in this folder becomes an accessible route in your application.


Data fetching in this version is primarily revolved around two methods -> getStaticProps for static generation and getServerSideProps for server side rendering:

getStaticProps

getStaticProps is used to generate static pages at the build time. This method is often used for pages that do not require frequently updated data.

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

  return {
    props: {
      posts,
    },
  }
}

function Posts({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  )
}

export default Posts;

getServerSideProps

getServerSideProps allows you to generate a page with each request, which is useful for pages requiring data that is always up to date.

export async function getServerSideProps(context) {
  const res = await fetch(`https://api.com/profile/${context.params.id}`)
  const data = await res.json()

  return {
    props: {
      profile: data,
    },
  }
}

function Profile({ profile }) {
  return (
    <div>
      <h1>{profile.name}</h1>
      <p>{profile.bio}</p>
    </div>
  )
}

export default Profile;

For both methods mentioned above, the utility functions of fetching must return the props to Server Components as a value.

Data fetching on Next.js 13/14

With the release of versions 13 and 14, it has introduced significant changes in the realm of data fetching, particularly React Server Components and Incremental Static Regeneration (ISR).

Server Components in Next.js 13/14

React Server Components represent a major shift in how developers can build and optimize their applications. Unlike traditional components, which run on both the server and the client, Server Components execute only on the server side. This approach offers several benefits, including reduced bundle sizes and enhanced performance.

Example of a Server Component

The new app/ directory introduces support for React's new Server Components architecture. Consider a simple Server Component that fetches and displays user data:

import { fetchUserData } from '../lib/data';

function UserList() {
    const userData = fetchUserData();
    return (
        <ul>
            {userData.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}

export default UserList;

In this example, UserList is a Server component. It fetches user data on the server and renders a list. This data fetching and rendering happen entirely on the server, meaning the client receives only the final HTML, reducing the amount of JavaScript sent to the browser.

Incremental Static Regeneration

ISR is another powerful feature in Next.js 13/14. It allows developers to update static content after it has been built, combining the benefits of static generation with on-demand rendering.

export async function getStaticProps() {
    const posts = await fetchPosts();
    return {
        props: { posts },
        revalidate: 10
    };
}

function Posts({ posts }) {
    return (
        <div>
            {posts.map(post => (
                <article key={post.id}>
                    <h2>{post.title}</h2>
                    <p>{post.content}</p>
                </article>
            ))}
        </div>
    );
}

export default Posts;

In this ISR example, getStaticProps fetches posts and enables revalidation every 10 seconds. This means the page will be regenerated at most every 10 seconds if there are requests for it, ensuring the content is up-to-date.


While Server Components and ISR are major highlights, Next.js 13/14 also introduced several other features:

For comments, please send me an dm through contact section.