cache·续
[!INFO]
Caching asynchronous work
When evaluating an asynchronous function, you will receive a Promise for that work. The promise holds the state of that work (pending, fulfilled, failed) and its eventual settled result.
In this example, the asynchronous function <CodeStep step={1}>
fetchData</CodeStep> returns a promise that is awaiting thefetch.
``js [[1, 1, "fetchData()"], [2, 8, "getData()"], [3, 10, "getData()"]] async function fetchData() { return await fetch(https://...`); }
const getData = cache(fetchData);
async function MyComponent() { getData(); // ... some computational work await getData(); // ... }
>
> In calling <CodeStep step={2}>`getData`</CodeStep> the first time, the promise returned from <CodeStep step={1}>`fetchData`</CodeStep> is cached. Subsequent look-ups will then return the same promise.
>
> Notice that the first <CodeStep step={2}>`getData`</CodeStep> call does not `await` whereas the <CodeStep step={3}>second</CodeStep> does. [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) is a JavaScript operator that will wait and return the settled result of the promise. The first <CodeStep step={2}>`getData`</CodeStep> call simply initiates the `fetch` to cache the promise for the second <CodeStep step={3}>`getData`</CodeStep> to look-up.
>
> If by the <CodeStep step={3}>second call</CodeStep> the promise is still _pending_, then `await` will pause for the result. The optimization is that while we wait on the `fetch`, React can continue with computational work, thus reducing the wait time for the <CodeStep step={3}>second call</CodeStep>.
>
> If the promise is already settled, either to an error or the _fulfilled_ result, `await` will return that value immediately. In both outcomes, there is a performance benefit.
> [!WARNING]
>
> ##### Calling a memoized function outside of a component will not use the cache.
>
```jsx [[1, 3, "getUser"]]
import {cache} from 'react';
const getUser = cache(async (userId) => {
return await db.user.query(userId);
});
// 🚩 Wrong: Calling memoized function outside of component will not memoize.
getUser('demo-id');
async function DemoProfile() {
// ✅ Good: `getUser` will memoize.
const user = await getUser('demo-id');
return <Profile user={user} />;
}
React only provides cache access to the memoized function in a component. When calling <CodeStep step={1}>
getUser</CodeStep> outside of a component, it will still evaluate the function but not read or update the cache.This is because cache access is provided through a context which is only accessible from a component.
[!INFO]
When should I use
cache,memo, oruseMemo?All mentioned APIs offer memoization but the difference is what they're intended to memoize, who can access the cache, and when their cache is invalidated.
useMemoIn general, you should use
useMemofor caching an expensive computation in a Client Component across renders. As an example, to memoize a transformation of data within a component.```jsx {expectedErrors: {'react-compiler': [4]}} {4} 'use client';
function WeatherReport({record}) { const avgTemp = useMemo(() => calculateAvg(record), record); // ... }
function App() {
const record = getRecord();
return (
<>
> In this example, `App` renders two `WeatherReport`s with the same record. Even though both components do the same work, they cannot share work. `useMemo`'s cache is only local to the component.
>
> However, `useMemo` does ensure that if `App` re-renders and the `record` object doesn't change, each component instance would skip work and use the memoized value of `avgTemp`. `useMemo` will only cache the last computation of `avgTemp` with the given dependencies.
>
> #### `cache`
>
> In general, you should use `cache` in Server Components to memoize work that can be shared across components.
>
```js [[1, 12, "<WeatherReport city={city} />"], [3, 13, "<WeatherReport city={city} />"], [2, 1, "cache(fetchReport)"]]
const cachedFetchReport = cache(fetchReport);
function WeatherReport({city}) {
const report = cachedFetchReport(city);
// ...
}
function App() {
const city = "Los Angeles";
return (
<>
<WeatherReport city={city} />
<WeatherReport city={city} />
</>
);
}
Re-writing the previous example to use
cache, in this case the <CodeStep step={3}>second instance ofWeatherReport</CodeStep> will be able to skip duplicate work and read from the same cache as the <CodeStep step={1}>firstWeatherReport</CodeStep>. Another difference from the previous example is thatcacheis also recommended for <CodeStep step={2}>memoizing data fetches</CodeStep>, unlikeuseMemowhich should only be used for computations.At this time,
cacheshould only be used in Server Components and the cache will be invalidated across server requests.
memoYou should use
memoto prevent a component re-rendering if its props are unchanged.
'use client';
function WeatherReport({record}) {
const avgTemp = calculateAvg(record);
// ...
}
const MemoWeatherReport = memo(WeatherReport);
function App() {
const record = getRecord();
return (
<>
<MemoWeatherReport record={record} />
<MemoWeatherReport record={record} />
</>
);
}
In this example, both
MemoWeatherReportcomponents will callcalculateAvgwhen first rendered. However, ifAppre-renders, with no changes torecord, none of the props have changed andMemoWeatherReportwill not re-render.Compared to
useMemo,memomemoizes the component render based on props vs. specific computations. Similar touseMemo, the memoized component only caches the last render with the last prop values. Once the props change, the cache invalidates and the component re-renders.
Troubleshooting
My memoized function still runs even though I've called it with the same arguments
See prior mentioned pitfalls * Calling different memoized functions will read from different caches. * Calling a memoized function outside of a component will not use the cache.
If none of the above apply, it may be a problem with how React checks if something exists in cache.
If your arguments are not primitives (ex. objects, functions, arrays), ensure you're passing the same object reference.
When calling a memoized function, React will look up the input arguments to see if a result is already cached. React will use shallow equality of the arguments to determine if there is a cache hit.
import {cache} from 'react';
const calculateNorm = cache((vector) => {
// ...
});
function MapMarker(props) {
// 🚩 Wrong: props is an object that changes every render.
const length = calculateNorm(props);
// ...
}
function App() {
return (
<>
<MapMarker x={10} y={10} z={10} />
<MapMarker x={10} y={10} z={10} />
</>
);
}
In this case the two MapMarkers look like they're doing the same work and calling calculateNorm with the same value of {x: 10, y: 10, z:10}. Even though the objects contain the same values, they are not the same object reference as each component creates its own props object.
React will call Object.is on the input to verify if there is a cache hit.
```js {3,9} import {cache} from 'react';
const calculateNorm = cache((x, y, z) => { // ... });
function MapMarker(props) { // ✅ Good: Pass primitives to memoized function const length = calculateNorm(props.x, props.y, props.z); // ... }
function App() {
return (
<>
One way to address this could be to pass the vector dimensions to `calculateNorm`. This works because the dimensions themselves are primitives.
Another solution may be to pass the vector object itself as a prop to the component. We'll need to pass the same object to both component instances.
```js {3,9,14}
import {cache} from 'react';
const calculateNorm = cache((vector) => {
// ...
});
function MapMarker(props) {
// ✅ Good: Pass the same `vector` object
const length = calculateNorm(props.vector);
// ...
}
function App() {
const vector = [10, 10, 10];
return (
<>
<MapMarker vector={vector} />
<MapMarker vector={vector} />
</>
);
}
