SWR
Lightweight data fetching with stale-while-revalidate caching.
What it is
SWR (stale-while-revalidate) is a React Hooks library for data fetching that provides caching, revalidation, focus tracking, and automatic retries. It simplifies fetching remote data and keeps UI in sync with the latest data.
SWR uses the `useSWR` hook to fetch data. You pass a key (usually the API URL) and a fetcher function. It returns data, error, and status, while automatically handling caching, revalidation, and retries.
- Licence
- MIT
- Maintained by
- Vercel
When to use it
The question documentation cannot answer for you — because it cannot recommend something else.
Reach for it when
- You want caching and revalidation without React Query's larger API surface
- The project is already on Next.js, where it fits naturally
Look elsewhere when
- You need advanced mutation handling, offline support or a rich query cache — React Query goes further
Installation
npm install swrGetting started
The smallest useful thing you can do with it, and what each part means.
import useSWR from 'swr';
const fetcher = url => fetch(url).then(res => res.json());
function Profile() {
const { data, error } = useSWR('/api/user', fetcher);
if (error) return <div>Failed to load</div>;
if (!data) return <div>Loading...</div>;
return <div>Hello {data.name}</div>;
}Advanced usage
Where the library earns its place over a simpler alternative.
const { data } = useSWR('/api/todos', fetcher, { refreshInterval: 5000 });const { data } = useSWR(userId ? `/api/user/${userId}` : null, fetcher);const { data, error } = useSWR('/api/posts', fetcher, {
onErrorRetry: (error, key, config, revalidate, { retryCount }) => {
if (retryCount >= 3) return;
setTimeout(() => revalidate({ retryCount }), 5000);
}
});import useSWR, { mutate } from 'swr';
const { data } = useSWR('/api/user', fetcher);
function updateName(newName) {
mutate('/api/user', { ...data, name: newName }, false);
fetch('/api/user', { method: 'POST', body: JSON.stringify({ name: newName }) }).then(() => mutate('/api/user'));
}Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- Network failure / fetch error
- Handle errors using the `error` object returned by `useSWR` and optionally retry requests.
- Data not updating
- Use `mutate` or `refreshInterval` to ensure the UI revalidates and updates cached data.
- Infinite loop fetching
- Ensure conditional keys are used to prevent fetching with undefined/null values.
Best practices
- Use `fetcher` functions consistently across your app for caching benefits.
- Combine SWR with React Suspense for better loading handling.
- Leverage `mutate` for optimistic UI updates.
- Use `dedupingInterval` to prevent duplicate requests.
- Use error retries and revalidation for robust data fetching.
Alternatives
Comparable options, and the reason you would pick one over the other.
Background
Why it exists, and what it was reacting to.
SWR was created by the Vercel team to offer a simple, efficient, and declarative way to fetch data in React applications. Inspired by HTTP cache strategies, SWR focuses on returning cached data first, then revalidating in the background, providing both speed and freshness.
