0
0
NextJSframework~5 mins

Parallel data fetching in NextJS

Choose your learning style9 modes available
Introduction

Parallel data fetching helps get multiple pieces of data at the same time. This makes your app faster because it does not wait for one request to finish before starting the next.

When your page needs data from several APIs or sources at once.
When you want to load user info and product details together.
When you want to show multiple lists or sections that come from different places.
When you want to reduce waiting time for users by fetching data simultaneously.
Syntax
NextJS
const [data1, data2] = await Promise.all([fetch(url1).then(res => res.json()), fetch(url2).then(res => res.json())]);
Use Promise.all to run multiple fetch requests at the same time.
Each fetch returns a promise, and Promise.all waits for all to finish.
Examples
This fetches user info and their posts at the same time.
NextJS
const [user, posts] = await Promise.all([
  fetch('https://jsonplaceholder.typicode.com/users/1').then(res => res.json()),
  fetch('https://jsonplaceholder.typicode.com/posts?userId=1').then(res => res.json())
]);
This fetches comments and albums simultaneously.
NextJS
const [comments, albums] = await Promise.all([
  fetch('https://jsonplaceholder.typicode.com/comments?postId=1').then(res => res.json()),
  fetch('https://jsonplaceholder.typicode.com/albums?userId=1').then(res => res.json())
]);
Sample Program

This Next.js page fetches user info and their posts at the same time using Promise.all. It then shows the user's name and email, followed by a list of their post titles.

NextJS
import React from 'react';

export default async function Page() {
  const [user, posts] = await Promise.all([
    fetch('https://jsonplaceholder.typicode.com/users/1').then(res => res.json()),
    fetch('https://jsonplaceholder.typicode.com/posts?userId=1').then(res => res.json())
  ]);

  return (
    <main>
      <h1>User Info</h1>
      <p>Name: {user.name}</p>
      <p>Email: {user.email}</p>

      <h2>Posts</h2>
      <ul>
        {posts.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </main>
  );
}
OutputSuccess
Important Notes

Always handle errors when fetching data to avoid app crashes.

Parallel fetching is faster but be careful not to overload the server with too many requests.

Summary

Parallel data fetching gets multiple data pieces at once to save time.

Use Promise.all with multiple fetch calls for this.

This improves user experience by loading data faster.