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.cacheis isolated: values cached outside are not visible inside. Pass data as arguments instead.
Compared to other caches
| Tool | Scope | Lifetime |
|---|---|---|
React.cache | one request | that render |
"use cache" | shared across requests | cacheLife |
useMemo | one Client Component | while 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.ts2import "server-only";3import { cache } from "react";4import { db } from "@/lib/db";56// Module level: one cache shared by every caller in the same request7export const getUser = cache(async (id: string) => {8 console.log("DB query for", id); // logs once per request, not three times9 return db.user.findUnique({ where: { id } });10});1112export const preloadUser = (id: string) => {13 void getUser(id); // start early, await later14};1516// 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.