Data Fetching & APIs
React SWR Data Fetching
SWR is a small data-fetching library built on the stale-while-revalidate idea: show cached data immediately, fetch fresh data in the background, then update the screen when it arrives.
What is SWR Data Fetching in React?
SWR is a small data-fetching library built on the stale-while-revalidate idea: show cached data immediately, fetch fresh data in the background, then update the screen when it arrives.
SWR Data Fetching example
JSX
import useSWR from 'swr';
const fetcher = url => fetch(url).then(r => r.json());
function Profile() {
const { data, error, isLoading, mutate } = useSWR('/api/me', fetcher);
if (isLoading) return <Skeleton />;
if (error) return <p>Failed to load</p>;
return <h1>{data.name}</h1>;
}Key points to remember
- Requests for the same key are deduplicated across components automatically.
- It revalidates on window focus and on network reconnect by default.
- mutate updates the cache locally for optimistic UI.
- Passing null as the key skips the request — useful for dependent fetches.
SWR vs TanStack Query
| SWR | TanStack Query | |
|---|---|---|
| Size | very small | larger |
| Devtools | basic | excellent |
| Mutations | manual via mutate | first-class useMutation |
| Best for | simple reads | complex caching and writes |
React SWR Data Fetching— Interview Questions & FAQs
What does SWR stand for?+
Stale-while-revalidate — an HTTP caching strategy where the cached value is served immediately while a background request checks for a newer one.
