Share a data snapshot
Several Server Components request the same resource during one render.
React 19+ · Function
cache memoizes a function's results for React Server Components during a server request. Matching arguments reuse prior work, while cache misses execute and store the function result.
Use cache to wrap a function whose data fetch or computation may be requested repeatedly by React Server Components. React memoizes results by arguments during a server request, allowing components in that render to reuse the same work.
const cachedFn = cache(fn)| Name | Type | Description |
|---|---|---|
fn | function | The function whose results React should memoize; it may accept any arguments and return any value. |
A memoized version of fn with the same type signature; creating it does not call fn.
import { cache } from 'react';
const getUser = cache(async (id: string) => {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) throw new Error('Request failed');
return response.json() as Promise<{ id: string; name: string }>;
});
export default async function Profile({ id }: { id: string }) {
const user = await getUser(id);
return <h1>{user.name}</h1>;
}This Server Component can call the cached function from multiple components during one server render; identical arguments reuse the result.
Several Server Components request the same resource during one render.
An expensive server-side calculation is repeated with identical inputs.
A tree needs one reusable data-access abstraction.
cache do?cache(fn) returns another function with the same type signature and does not invoke fn immediately. On a call, React returns a stored result for matching arguments; otherwise it runs fn, stores the result, and returns it.
Follow-up: How is the cache scoped? It is invalidated for every server request, so it is not a general persistent application cache.
Create the cached wrapper outside components. This gives multiple Server Components access to the same memoized function during a server render and avoids duplicate work for equal arguments.
Follow-up: What happens if two wrappers are created from the same original function? They are distinct memoized functions and do not share a cache.
The wrapped function may accept any arguments and return any value. React uses the arguments passed to the cached function to determine whether a result is already available.
Follow-up: Can a component call the wrapper and still miss the cache? Yes, calls made outside component execution evaluate the function without reading or updating React's cache.
cacheSignalfetchReact Server Components