Next.jsMedium

How do you use React.cache in Next.js?

React.cache wraps a function so that repeated calls with the same arguments during one server request return the same result. Use it to deduplicate database or SDK calls across components in a render. It is per-request memoization, not a persistent cache.

Why you need it

fetch calls are memoized automatically, but ORM queries and SDK calls are not. If a layout, page and generateMetadata all call getUser(id), React.cache makes it one query.

Rules

  • Works only in Server Components (and functions they call).
  • Arguments are compared by identity (Object.is), so pass primitives. Two different object literals with the same content are two cache misses.
  • Define the cached function at module level. Creating it inside a component makes a new cache each render.
  • The cache is discarded after the request, so nothing leaks between users.
  • Inside a "use cache" scope, React.cache is isolated: values cached outside are not visible inside. Pass data as arguments instead.

Compared to other caches

ToolScopeLifetime
React.cacheone requestthat render
"use cache"shared across requestscacheLife
useMemoone Client Componentwhile mounted

Preload pattern

Call a cached function early without awaiting (void getUser(id)) to start the request, then await it later in a child. The child gets the already in-flight promise.

Code example

tsx
1// lib/user.ts
2import "server-only";
3import { cache } from "react";
4import { db } from "@/lib/db";
5
6// Module level: one cache shared by every caller in the same request
7export const getUser = cache(async (id: string) => {
8 console.log("DB query for", id); // logs once per request, not three times
9 return db.user.findUnique({ where: { id } });
10});
11
12export const preloadUser = (id: string) => {
13 void getUser(id); // start early, await later
14};
15
16// app/users/[id]/layout.tsx -> await getUser(id) (query runs)
17// app/users/[id]/page.tsx -> await getUser(id) (deduplicated)
18// generateMetadata -> await getUser(id) (deduplicated)

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app