use·续1
[!INFO]
Why are Promises recreated on every render?
React doesn't preserve state for renders that suspended before mounting. After each suspension, React retries rendering from scratch, so any Promise created during render is recreated.
Common ways a Promise can be unintentionally recreated during render:
function Albums() {
// 🔴 `fetch` creates a new Promise on every render.
const albums = use(fetch('/albums'));
// 🔴 Uncached `async` function calls create a new Promise on every render.
const albums = use((async () => {
const res = await fetch('/albums');
return res.json();
})());
// 🔴 Adding `.then` returns a new Promise on every render,
// even if `fetchData` is cached.
const albums = use(fetchData('/albums').then(res => res.json()));
// ...
}
Ideally, Promises are created before rendering, such as in an event handler, a route loader, or a Server Component, and passed to the component that calls
use. Fetching lazily in render delays network requests and can create waterfalls.
// ✅ fetchData reads the Promise from a cache.
const albums = use(fetchData('/albums'));
Caching Promises for Client Components
Promises passed to use in Client Components must be cached so the same Promise instance is reused across re-renders. If a new Promise is created directly in render, React will display the Suspense fallback on every re-render.
// ✅ Cache the Promise so the same one is reused across renders
let cache = new Map();
export function fetchData(url) {
if (!cache.has(url)) {
cache.set(url, getData(url));
}
return cache.get(url);
}
The fetchData function returns the same Promise each time it's called with the same URL. When use receives the same Promise on a re-render, it reads the already-resolved value synchronously without suspending.
[!NOTE]
The way you cache Promises depends on the framework you use with Suspense. Frameworks typically provide built-in caching mechanisms. If you don't use a framework, you can use a simple module-level cache like the one above, or a Suspense-enabled data source.
In the example below, clicking "Re-render" updates state in App and triggers a re-render. Because fetchData returns the same cached Promise, Albums reads the value synchronously instead of showing the Suspense fallback again.
```js src/App.js active import { use, Suspense, useState } from 'react'; import { fetchData } from './data.js';
export default function App() { const [count, setCount] = useState(0); return ( <>
Render count: {count}
<Suspense fallback={Loading...
}>function Albums() { const albums = use(fetchData('/albums')); return (
-
{albums.map(album => (
- {album.title} ({album.year}) ))}
```js src/data.js hidden
// Note: the way you would do data fetching depends on
// the framework that you use together with Suspense.
// Normally, the caching logic would be inside a framework.
let cache = new Map();
export function fetchData(url) {
if (!cache.has(url)) {
cache.set(url, getData(url));
}
return cache.get(url);
}
async function getData(url) {
if (url === '/albums') {
return await getAlbums();
} else {
throw Error('Not implemented');
}
}
async function getAlbums() {
// Add a fake delay to make waiting noticeable.
await new Promise(resolve => {
setTimeout(resolve, 1000);
});
return [{
id: 13,
title: 'Let It Be',
year: 1970
}, {
id: 12,
title: 'Abbey Road',
year: 1969
}, {
id: 11,
title: 'Yellow Submarine',
year: 1969
}];
}
[!INFO]
How to implement a promise cache
A basic cache stores the Promise keyed by URL so the same instance is reused across renders. To also avoid unnecessary Suspense fallbacks when data is already available, you can set
statusandvalue(orreason) fields on the Promise. React checks these fields whenuseis called: ifstatusis'fulfilled', it readsvaluesynchronously without suspending. Ifstatusis'rejected', it throwsreason. If the field is missing or'pending', it suspends.
let cache = new Map();
function fetchData(url) {
if (!cache.has(url)) {
const promise = getData(url);
promise.status = 'pending';
promise.then(
value => {
promise.status = 'fulfilled';
promise.value = value;
},
reason => {
promise.status = 'rejected';
promise.reason = reason;
},
);
cache.set(url, promise);
}
return cache.get(url);
}
This is primarily useful for library authors building Suspense-compatible data layers. React will set the
statusfield itself on Promises that don't have it, but setting it yourself avoids an extra render when the data is already available.This cache pattern is the foundation for re-fetching data (where changing the cache key triggers a new fetch) and preloading data on hover (where calling
fetchDataearly means the Promise may already be resolved by the timeusereads it).[!WARNING]
Don't skip calling
usebased on whether a Promise is already settled.Unlike other hooks,
usecan be called inside conditions and loops — but it must always be called for the Promise itself. Never readpromise.statusorpromise.valuedirectly to bypassuse; always pass the Promise touseand let React handle it.
// 🔴 Don't bypass `use` by reading promise status directly
if (promise.status === 'fulfilled') {
return promise.value;
}
const value = use(promise);
// ✅ Pass the promise to `use` and let React track the promise
const value = use(promise);
Bypassing
usethis way can break React Suspense optimizations and Suspense features for React DevTools. You canuse(promise)conditionally, but don't conditionallyuse(promise)based on the promise itself.
Re-fetching data in Client Components
To refresh data at the same URL (for example, with a "Refresh" button), invalidate the cache entry and start a new fetch inside a startTransition. Store the resulting Promise in state to trigger a re-render. While the new Promise is pending, React keeps showing the existing content because the update is inside a Transition.
function App() {
const [albumsPromise, setAlbumsPromise] = useState(fetchData('/albums'));
const [isPending, startTransition] = useTransition();
function handleRefresh() {
startTransition(() => {
setAlbumsPromise(refetchData('/albums'));
});
}
// ...
}
refetchData clears the old cache entry and starts a new fetch at the same URL. Storing the resulting Promise in state triggers a re-render inside the Transition. On re-render, Albums receives the new Promise and use suspends on it while React keeps showing the old content.
```js src/App.js active import { Suspense, useState, useTransition } from 'react'; import { use } from 'react'; import { fetchData, refetchData } from './data.js';
export default function App() { const [albumsPromise, setAlbumsPromise] = useState( () => fetchData('/the-beatles/albums') ); const [isPending, startTransition] = useTransition();
function handleRefresh() { startTransition(() => { setAlbumsPromise(refetchData('/the-beatles/albums')); }); }
return ( <>
function Albums({ albumsPromise }) { const albums = use(albumsPromise); return (
-
{albums.map(album => (
- {album.title} ({album.year}) ))}
function Loading() { return
Loading...
; }
```js src/data.js hidden
// Note: the way you would do data fetching depends on
// the framework that you use together with Suspense.
// Normally, the caching logic would be inside a framework.
let cache = new Map();
export function fetchData(url) {
if (!cache.has(url)) {
cache.set(url, getData(url));
}
return cache.get(url);
}
export function refetchData(url) {
cache.delete(url);
return fetchData(url);
}
async function getData(url) {
if (url.startsWith('/the-beatles/albums')) {
return await getAlbums();
} else {
throw Error('Not implemented');
}
}
async function getAlbums() {
// Add a fake delay to make waiting noticeable.
await new Promise(resolve => {
setTimeout(resolve, 1000);
});
return [{
id: 13,
title: 'Let It Be',
year: 1970
}, {
id: 12,
title: 'Abbey Road',
year: 1969
}, {
id: 11,
title: 'Yellow Submarine',
year: 1969
}, {
id: 10,
title: 'The Beatles',
year: 1968
}, {
id: 9,
title: 'Magical Mystery Tour',
year: 1967
}];
}
button { margin-bottom: 10px; }
[!NOTE]
Frameworks that support Suspense typically provide their own caching and invalidation mechanisms. The custom cache above is useful for understanding the pattern, but in practice prefer your framework's data fetching solution.
Preloading data on hover
You can start loading data before it's needed by calling fetchData during a hover event. Since fetchData caches the Promise, the data may already be available by the time the user clicks. If the Promise has resolved by the time use reads it, React renders the component immediately without showing a Suspense fallback.
<button
onMouseEnter={() => fetchData(`/${id}/albums`)}
onClick={() => {
startTransition(() => {
setArtistId(id);
});
}}
>
In this example, hovering over an artist button starts fetching their albums in the background. Without hovering first, clicking shows a loading fallback. Try hovering over a button for a moment before clicking to see the difference.
```js src/App.js active import { Suspense, useState, useTransition } from 'react'; import Albums from './Albums.js'; import { fetchData } from './data.js';
export default function App() { const [artistId, setArtistId] = useState('the-beatles'); const [isPending, startTransition] = useTransition();
return ( <>
function Loading() { return
Loading...
; }
```js src/Albums.js
import { use } from 'react';
import { fetchData } from './data.js';
export default function Albums({ artistId }) {
const albums = use(fetchData(`/${artistId}/albums`));
return (
<ul>
{albums.map(album => (
<li key={album.id}>
{album.title} ({album.year})
</li>
))}
</ul>
);
}
```js src/data.js hidden // Note: the way you would do data fetching depends on // the framework that you use together with Suspense. // Normally, the caching logic would be inside a framework.
let cache = new Map();
export function fetchData(url) {
if (!cache.has(url)) {
const promise = getData(url);
// Set status fields so React can read the value
// synchronously if the Promise resolves before
// use is called (e.g. when preloading on hover).
promise.status = 'pending';
promise.then(
value => {
promise.status = 'fulfilled';
promise.value = value;
},
reason => {
promise.status = 'rejected';
promise.reason = reason;
},
);
cache.set(url, promise);
}
return cache.get(url);
}
async function getData(url) { if (url.startsWith('/the-beatles/albums')) { return await getAlbums('the-beatles'); } else if (url.startsWith('/led-zeppelin/albums')) { return await getAlbums('led-zeppelin'); } else if (url.startsWith('/pink-floyd/albums')) { return await getAlbums('pink-floyd'); } else { throw Error('Not implemented'); } }
async function getAlbums(artistId) { // Add a fake delay to make waiting noticeable. await new Promise(resolve => { setTimeout(resolve, 800); });
if (artistId === 'the-beatles') { return [{ id: 13, title: 'Let It Be', year: 1970 }, { id: 12, title: 'Abbey Road', year: 1969 }, { id: 11, title: 'Yellow Submarine', year: 1969 }]; } else if (artistId === 'led-zeppelin') { return [{ id: 10, title: 'Coda', year: 1982 }, { id: 9, title: 'In Through the Out Door', year: 1979 }, { id: 8, title: 'Presence', year: 1976 }]; } else { return [{ id: 7, title: 'The Wall', year: 1979 }, { id: 6, title: 'Animals', year: 1977 }, { id: 5, title: 'Wish You Were Here', year: 1975 }]; } } ```
