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.