Summary
Serve stale cache immediately while fetching fresh in background — great UX for non-critical data. User may briefly see outdated content — acceptable for feeds, not balances. HTTP Cache-Control: stale-while-revalidate and client libraries (SWR, TanStack Query staleTime). Tune staleTime vs gcTime consciously.
Code example
async function fetchWithSWR(key, fetcher, maxAgeMs = 60_000) {
const cached = store.get(key);
const isStale = !cached || Date.now() - cached.fetchedAt > maxAgeMs;
if (cached) {
if (isStale) fetcher(key).then((data) => store.set(key, { data, fetchedAt: Date.now() }));
return cached.data;
}
const data = await fetcher(key);
store.set(key, { data, fetchedAt: Date.now() });
return data;
}
Key points
- Serve stale cache immediately while fetching fresh in background — great UX for non-critical data.
- User may briefly see outdated content — acceptable for feeds, not balances.
- HTTP
Cache-Control: stale-while-revalidateand client libraries (SWR, TanStack QuerystaleTime). - Tune staleTime vs gcTime consciously.