Skip to the solution
MediumFrontend5 min read

What is request memoization in Next.js?

608 views

The problem

Question presented to candidate: "Three components on the same page each call fetch for the current user. How many network requests happen, and how would you get the same behaviour for a database query?"

What a strong answer should cover:

  • Next.js memoizes fetch GET requests with the same URL and options for the duration of one server render.
  • It applies across layouts, pages, Server Components, generateMetadata and generateStaticParams, but not in Route Handlers.
  • It is independent of the Data Cache: even no-store requests are deduplicated within a render.
  • For non-fetch work (ORM, SDK) wrap the function in React cache() to get the same per-request deduplication.
  • It resets for every request, so it is safe for per-user data.

Clarifying questions expected:

  • "Is it a fetch or a database call?" β€” only fetch is memoized automatically.
  • "Do the calls use exactly the same URL and options?" β€” any difference is a separate request.

Code / implementation expected: Yes β€” a React.cache-wrapped data function used in several components.

  • nextjs
  • request-memoization
  • fetch
  • caching

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read Β· 8 sections

Read the code

A per-request cached loader used in several places
// lib/user.ts
import { cache } from "react";
import "server-only";
import { db } from "@/lib/db";

export const getUser = cache(async (id: string) => {
  return db.user.findUnique({ where: { id } }); // runs once per request per id
});

// app/layout.tsx and app/page.tsx and app/Header.tsx can all do:
//   const user = await getUser(session.userId);
// -> one database query per request

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 62 of 129 in Next.js

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Next.js questions
Up nextMedium

What is next.config.js in Next.js and what are common configurations?

Continue