Nextjs Fundamentals · Data Fetching

Deduplicating requests

`React.cache`

Deduplicating requests

React memoises identical fetch calls for you, but data access that does not go through fetch — an ORM query, a database call, a filesystem read — gets no such help. If three components each call getUser(id), the query runs three times.

React.cache fixes that. Wrap the function and React deduplicates calls with the same arguments within a single render pass:

import { cache } from 'react';

export const getUser = cache(async (id: string) => {
  return db.query.users.findFirst({ where: eq(users.id, id) });
});

Now any Server Component can call getUser('1') directly, without prop drilling, and the underlying query runs once. The first caller's promise is shared with every later caller that passes the same id.

Two things to remember. React.cache is scoped to the current request only — each request gets a fresh memoisation scope and nothing is shared between requests. And it only deduplicates within one request; it is not a persistent cache. For caching across requests, use the use cache directive instead.

The pattern: wrap non-fetch data access in React.cache, then call it freely from anywhere in the tree.

You are about to answer a short quiz on React.cache.

  1. React.cache deduplicates calls with the same arguments within one render pass.
  2. You wrap a data-fetching function with ___ to deduplicate non-fetch data access.
  3. React.cache shares its results across different requests.
  4. React.cache is scoped to the current ___, so each one gets a fresh scope.
  5. Identical fetch calls are already memoised by React, so React.cache is mainly for ORM or database access.