Data Fetching with SWR
In this page:
const fetcher = url => fetch(url).then(res => res.json());
const { data, error, isLoading } = useSWR("/api/path", fetcher);
The Stale-While-Revalidate Idea
SWR's core idea, and its namesake, is showing cached (stale) data to the user immediately, while simultaneously firing off a fresh request in the background to revalidate it.
This makes the UI feel instant even on a slow connection, updating seamlessly once the fresh data arrives.
Example: The Stale-While-Revalidate Idea
// Run in your local React project (npm install required)
import useSWR from 'swr';
const fetcher = url => fetch(url).then(res => res.json());
function UserList() {
const { data, error, isLoading } = useSWR('/api/users', fetcher);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Failed to load</p>;
return <ul>{data.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}
⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.
The Key and Fetcher Pattern
useSWR takes two arguments: a key (usually the URL, used to identify and cache the request) and a fetcher function that actually performs the request.
SWR doesn't include a built-in fetcher — you provide a small function, often just a thin wrapper around fetch().
Example: The Key and Fetcher Pattern
// Run in your local React project (npm install required)
import useSWR from 'swr';
const fetcher = url => fetch(url).then(res => res.json());
function Profile({ userId }) {
const { data } = useSWR(userId ? `/api/users/${userId}` : null, fetcher);
return <p>{data ? data.name : 'No user selected'}</p>;
}
⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.
Automatic Background Revalidation
By default, SWR automatically refetches data in situations like the browser window regaining focus or the network reconnecting, keeping data fresh without any manual refresh logic.
These behaviors can be tuned via configuration options passed as a third argument.
Example: Automatic Background Revalidation
// Run in your local React project (npm install required)
import useSWR from 'swr';
const fetcher = url => fetch(url).then(res => res.json());
function LiveData() {
const { data } = useSWR('/api/stats', fetcher, {
revalidateOnFocus: true,
refreshInterval: 5000,
});
return <p>Stat value: {data?.value}</p>;
}
⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.
- Confusing SWR's key with a React Query query key syntax — SWR's key is usually just the URL string itself, not an array.
- Not understanding stale-while-revalidate — SWR intentionally shows old cached data first, then updates it, rather than always blocking on a fresh fetch.
- Forgetting the fetcher function isn't built in — you must provide one (often a simple fetch wrapper) yourself.
- SWR is a lightweight data-fetching library named after the stale-while-revalidate HTTP caching strategy.
- useSWR(key, fetcher) returns data, error, and isLoading, refetching automatically in the background.
- The key is typically the request URL itself, used to identify and cache each request.
- SWR shows cached (possibly stale) data immediately while silently fetching a fresh copy in the background.
Requires npm install swr — not available via CDN in this sandbox; works with React 16.8+.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: