CodePark/ questions / Data fetching & caching
START PRACTICINGPRACTICE
Frontend question · Next.js › Data fetching & caching

A layout, a page and generateMetadata all need the current user. How do you avoid fetching it three times?

// lib/user.ts
import { cache } from "react";

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

Use request memoization: call the same function in all three places, and only one request happens.

If the data comes from fetch, Next.js memoizes identical GET requests during a single server render. All three can call the same function. Only one network request is made.

If the data comes from a database or SDK, wrap the function in React's cache(). The first call in a request runs the query. Later calls with the same arguments return the same result.

This memoization lasts for one request only. It is separate from the persistent Data Cache. It lets you fetch data where you use it, instead of passing it down through many props (prop drilling).

  • Identical GET fetches are memoized during one render.
  • Use React cache() for ORM or SDK calls.
  • The memoization lasts for a single request and is not persistent.
  • It lets you fetch data where it is used instead of prop drilling.