cache
cache is only for use with React Server Components.
cache lets you cache the result of a data fetch or computation.
const cachedFn = cache(fn);
Reference
cache(fn)
Call cache outside of any components to create a version of the function with caching.
```js {4,7} import {cache} from 'react'; import calculateMetrics from 'lib/metrics';
const getMetrics = cache(calculateMetrics);
function Chart({data}) { const report = getMetrics(data); // ... }
When `getMetrics` is first called with `data`, `getMetrics` will call `calculateMetrics(data)` and store the result in cache. If `getMetrics` is called again with the same `data`, it will return the cached result instead of calling `calculateMetrics(data)` again.
[See more examples below.](#usage)
#### Parameters
- `fn`: The function you want to cache results for. `fn` can take any arguments and return any value.
#### Returns
`cache` returns a cached version of `fn` with the same type signature. It does not call `fn` in the process.
When calling `cachedFn` with given arguments, it first checks if a cached result exists in the cache. If a cached result exists, it returns the result. If not, it calls `fn` with the arguments, stores the result in the cache, and returns the result. The only time `fn` is called is when there is a cache miss.
> [!NOTE]
>
> The optimization of caching return values based on inputs is known as [_memoization_](https://en.wikipedia.org/wiki/Memoization). We refer to the function returned from `cache` as a memoized function.
>
#### Caveats
- React will invalidate the cache for all memoized functions for each server request.
- Each call to `cache` creates a new function. This means that calling `cache` with the same function multiple times will return different memoized functions that do not share the same cache.
- `cachedFn` will also cache errors. If `fn` throws an error for certain arguments, it will be cached, and the same error is re-thrown when `cachedFn` is called with those same arguments.
- `cache` is for use in [Server Components](/reference/rsc/server-components) only.
---
## Usage
### Cache an expensive computation
Use `cache` to skip duplicate work.
```js [[1, 7, "getUserMetrics(user)"],[2, 13, "getUserMetrics(user)"]]
import {cache} from 'react';
import calculateUserMetrics from 'lib/user';
const getUserMetrics = cache(calculateUserMetrics);
function Profile({user}) {
const metrics = getUserMetrics(user);
// ...
}
function TeamReport({users}) {
for (let user in users) {
const metrics = getUserMetrics(user);
// ...
}
// ...
}
If the same user object is rendered in both Profile and TeamReport, the two components can share work and only call calculateUserMetrics once for that user.
Assume Profile is rendered first. It will call <CodeStep step={1}>getUserMetrics</CodeStep>, and check if there is a cached result. Since it is the first time getUserMetrics is called with that user, there will be a cache miss. getUserMetrics will then call calculateUserMetrics with that user and write the result to cache.
When TeamReport renders its list of users and reaches the same user object, it will call <CodeStep step={2}>getUserMetrics</CodeStep> and read the result from cache.
If calculateUserMetrics can be aborted by passing an AbortSignal, you can use cacheSignal() to cancel the expensive computation if React has finished rendering. calculateUserMetrics may already handle cancellation internally by using cacheSignal directly.
[!WARNING]
Calling different memoized functions will read from different caches.
To access the same cache, components must call the same memoized function.
```js [[1, 7, "getWeekReport"], [1, 7, "cache(calculateWeekReport)"], [1, 8, "getWeekReport"]] // Temperature.js import {cache} from 'react'; import {calculateWeekReport} from './report';
export function Temperature({cityData}) {
// 🚩 Wrong: Calling cache in component creates new getWeekReport for each render
const getWeekReport = cache(calculateWeekReport);
const report = getWeekReport(cityData);
// ...
}
>
```js [[2, 6, "getWeekReport"], [2, 6, "cache(calculateWeekReport)"], [2, 9, "getWeekReport"]]
// Precipitation.js
import {cache} from 'react';
import {calculateWeekReport} from './report';
// 🚩 Wrong: `getWeekReport` is only accessible for `Precipitation` component.
const getWeekReport = cache(calculateWeekReport);
export function Precipitation({cityData}) {
const report = getWeekReport(cityData);
// ...
}
In the above example, <CodeStep step={2}>
Precipitation</CodeStep> and <CodeStep step={1}>Temperature</CodeStep> each callcacheto create a new memoized function with their own cache look-up. If both components render for the samecityData, they will do duplicate work to callcalculateWeekReport.In addition,
Temperaturecreates a <CodeStep step={1}>new memoized function</CodeStep> each time the component is rendered which doesn't allow for any cache sharing.To maximize cache hits and reduce work, the two components should call the same memoized function to access the same cache. Instead, define the memoized function in a dedicated module that can be
import-ed across components.```js [[3, 5, "export default cache(calculateWeekReport)"]] // getWeekReport.js import {cache} from 'react'; import {calculateWeekReport} from './report';
export default cache(calculateWeekReport);
>
```js [[3, 2, "getWeekReport", 0], [3, 5, "getWeekReport"]]
// Temperature.js
import getWeekReport from './getWeekReport';
export default function Temperature({cityData}) {
const report = getWeekReport(cityData);
// ...
}
```js [[3, 2, "getWeekReport", 0], [3, 5, "getWeekReport"]] // Precipitation.js import getWeekReport from './getWeekReport';
export default function Precipitation({cityData}) { const report = getWeekReport(cityData); // ... }
> Here, both components call the <CodeStep step={3}>same memoized function</CodeStep> exported from `./getWeekReport.js` to read and write to the same cache.
### Share a snapshot of data
To share a snapshot of data between components, call `cache` with a data-fetching function like `fetch`. When multiple components make the same data fetch, only one request is made and the data returned is cached and shared across components. All components refer to the same snapshot of data across the server render.
```js [[1, 4, "city"], [1, 5, "fetchTemperature(city)"], [2, 4, "getTemperature"], [2, 9, "getTemperature"], [1, 9, "city"], [2, 14, "getTemperature"], [1, 14, "city"]]
import {cache} from 'react';
import {fetchTemperature} from './api.js';
const getTemperature = cache(async (city) => {
return await fetchTemperature(city);
});
async function AnimatedWeatherCard({city}) {
const temperature = await getTemperature(city);
// ...
}
async function MinimalWeatherCard({city}) {
const temperature = await getTemperature(city);
// ...
}
If AnimatedWeatherCard and MinimalWeatherCard both render for the same <CodeStep step={1}>city</CodeStep>, they will receive the same snapshot of data from the <CodeStep step={2}>memoized function</CodeStep>.
If AnimatedWeatherCard and MinimalWeatherCard supply different <CodeStep step={1}>city</CodeStep> arguments to <CodeStep step={2}>getTemperature</CodeStep>, then fetchTemperature will be called twice and each call site will receive different data.
The <CodeStep step={1}>city</CodeStep> acts as a cache key.
[!NOTE]
<CodeStep step={3}>Asynchronous rendering</CodeStep> is only supported for Server Components.
```js [[3, 1, "async"], [3, 2, "await"]] async function AnimatedWeatherCard({city}) { const temperature = await getTemperature(city); // ... }
>
> To render components that use asynchronous data in Client Components, see [`use()` documentation](/reference/react/use).
>
### Preload data
By caching a long-running data fetch, you can kick off asynchronous work prior to rendering the component.
```jsx [[2, 6, "await getUser(id)"], [1, 17, "getUser(id)"]]
const getUser = cache(async (id) => {
return await db.user.query(id);
});
async function Profile({id}) {
const user = await getUser(id);
return (
<section>
<img src={user.profilePic} />
<h2>{user.name}</h2>
</section>
);
}
function Page({id}) {
// ✅ Good: start fetching the user data
getUser(id);
// ... some computational work
return (
<>
<Profile id={id} />
</>
);
}
When rendering Page, the component calls <CodeStep step={1}>getUser</CodeStep> but note that it doesn't use the returned data. This early <CodeStep step={1}>getUser</CodeStep> call kicks off the asynchronous database query that occurs while Page is doing other computational work and rendering children.
When rendering Profile, we call <CodeStep step={2}>getUser</CodeStep> again. If the initial <CodeStep step={1}>getUser</CodeStep> call has already returned and cached the user data, when Profile <CodeStep step={2}>asks and waits for this data</CodeStep>, it can simply read from the cache without requiring another remote procedure call. If the <CodeStep step={1}> initial data request</CodeStep> hasn't been completed, preloading data in this pattern reduces delay in data-fetching.
