javascript / expert
Snippet
Suspense-Compatible Resource Caching
To integrate with React Suspense manually, a data fetcher must 'throw' a promise while pending. This pattern creates a simple but powerful bridge for async resources.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const cache = new Map();function fetchData(url) {if (cache.has(url)) return cache.get(url);const promise = fetch(url).then(r => r.json()).then(data => cache.set(url, { status: 'success', data })).catch(error => cache.set(url, { status: 'error', error }));cache.set(url, { status: 'pending', promise });throw promise;}function ResourceComponent({ url }) {const resource = fetchData(url);if (resource.status === 'pending') throw resource.promise;return <div>{resource.data.title}</div>;}
react
Breakdown
1
throw promise
The mechanism that signals to React that the component is not ready to render.
2
cache.set(url, { status: 'success', data })
Stores the result to ensure subsequent renders return the data immediately.
3
if (cache.has(url)) return cache.get(url)
Prevents redundant network requests by checking the local cache first.