Skip to content
Tutorials Center
My learning

Topics

React Reference ยท Top-Level React APIs

React cache() function

Reference for React cache: memoize a function per server request so Server Components share one fetch, how arguments are compared, and its client behavior.

cache wraps a function so that repeated calls with the same arguments, during one server render, run the function only once and share the result. It is meant for Server Components: several components in one page can each ask for "the current user" with the same call, and the database is hit a single time.

The cache lives for one request. It is not a shared, long-lived cache like a CDN or an in-memory store, and the next request starts empty. Outside Server Components the function does not cache anything: in the browser, cache(fn) simply calls fn every time.

JSX
import { cache } from 'react';

export const getUser = cache(async (id) => {
  return db.users.find(id);
});

Try it

The real behavior needs a server renderer, so this example uses a small stand-in that follows the same rules: one cache per "request", results shared by equal arguments, and a different function instance means a different cache.

Stand-in: one call per request
Stand-in: objects are compared by reference

Expected: the first example runs 2 queries (ids 1 and 2); the second runs 2 times, because the equal-looking copy is a different object.

Syntax

TypeScript
function cache<T extends (...args: any[]) => any>(fn: T): T;
Name Description
fn The function to memoize. It can take any arguments and may be async.

Returns: a function with the same signature. Calls with arguments that are equal (primitives by value, objects and functions by reference) return the earlier result. The result can be a promise, which components can read with use.

Usage notes

  • Server Components only. The cache is scoped to a server render and is invalidated for every new request. In client components, or outside React's server rendering, cache does nothing useful.
  • Define it at module level and export it, so every component imports the same cached function. Calling cache(fn) inside a component creates a new, empty cache on each render.
  • Each cache(fn) has its own store. Two separate wrappers around the same function do not share results.
  • Errors are cached too, so a failed call is not retried within the same request.
  • Object arguments are compared by reference. Passing { id: 1 } literals from several places misses the cache. Use primitive arguments such as ids.
  • It does not replace fetch caching or persistent caches. Use your framework's data cache or a store for cross-request caching.
  • Useful for preloading: call the cached function early (without awaiting) and read the result later; the later call reuses the in-flight promise.
  • Not the same as useMemo. useMemo caches per component instance in the client; cache shares across components in one server render.