Back to results for “Caching”
React › Data Fetching (React Query & SWR)

How does SWR's stale while revalidate strategy work, and why is it useful?

Advanced

Answer

SWR immediately shows any data it already has cached, even if it might be slightly outdated, while quietly fetching a fresh copy in the background at the same time. Once the fresh data arrives, the screen updates automatically. This gives users an instant response instead of a loading spinner, while still keeping the data reasonably up to date.
import useSWR from 'swr';

function Weather() {
  const { data } = useSWR('/api/weather', (url) => fetch(url).then((res) => res.json()));
  if (!data) return <p>Loading</p>;
  return <p>Temperature: {data.temp} degrees</p>;
}
Real-world example A weather app shows yesterday's cached temperature instantly when opened, then quietly updates to today's real temperature a moment later once the background request finishes, using SWR's stale while revalidate approach.

Common follow-ups: What does the name SWR actually stand for, and how does it relate to this behavior?;How would you force SWR to always fetch fresh data and skip showing the stale cache first?