Unlocking Performance in Next.js & React.js: A Simple Guide to Parallel Data Fetching
Image Credit: ChatGpt

Unlocking Performance in Next.js & React.js: A Simple Guide to Parallel Data Fetching

Why does my app still feel slow even when I’m using async/await properly?

Turns out, the way we write async code could still make our tasks run one after the other even when they don’t need to wait for each other. This subtle difference can drastically affect your app’s performance, especially in data-heavy pages or API-heavy components.


🧠 First, Let’s Recap: How Async Tasks Work

When you run asynchronous code in JavaScript (like fetch, setTimeout, fs.readFile, etc.), it:

  1. Starts the async task.
  2. Does not block the next line of code.
  3. Once the task finishes, its callback (like .then() or await) is queued in the event loop to be run later.

✅ So yes, async tasks don’t run immediately in the main thread, they go to the task queue (or microtask queue in case of promises).


👀 So What Is Parallel Data Fetching?

Parallel fetching means starting multiple async tasks at once, instead of waiting for one to finish before starting the next.

Think of it like this:

❌ Sequential (Not parallel)

const user = await fetch("/api/user"); // wait here 
const posts = await fetch("/api/posts"); // then wait again 
const comments = await fetch("/api/comments"); // then wait again        

This takes longer because you're waiting for each one in order.


✅ Parallel (Recommended)

const userPromise = fetch("/api/user"); 
const postsPromise = fetch("/api/posts"); 
const commentsPromise = fetch("/api/comments"); 

const [user, posts, comments] = await Promise.all([ 
    userPromise,
    postsPromise,
    commentsPromise, 
]);        

  • All 3 requests are fired off at once.
  • Then you await them all to finish.
  • This is faster, because they run in parallel even though JavaScript itself is single-threaded.


🧰 When Should You Use This?

  • Fetching multiple APIs in getServerSideProps, useEffect, or in Server Actions
  • Loading dashboard data
  • Performing multiple DB queries
  • You need all data before rendering the UI

🚫 Don’t use parallel fetching when:

  • One request depends on the result of another


🔥 So, are they really running in parallel?

Yes and no:

  • JavaScript is single-threaded, but…
  • Async tasks (like fetch) are handed off to the browser’s Web APIs or Node's libuv thread pool, they do the work in the background.
  • When they finish, the result is queued back for your code to await.

So while JavaScript doesn't do the work in parallel, the work is happening in parallel elsewhere, and JavaScript just picks up the results when they're ready.

But hey, you just unlocked a serious performance boost 💥


To view or add a comment, sign in

More articles by Precious Anuforo

Explore content categories