Language: JavaScript
Web
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.
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.
npm install swryarn add swrSWR 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.
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>;
}Uses `useSWR` to fetch user data from `/api/user`, showing loading, error, and fetched states.
const { data } = useSWR('/api/todos', fetcher, { refreshInterval: 5000 });Automatically re-fetches data every 5 seconds to keep UI updated.
const { data } = useSWR(userId ? `/api/user/${userId}` : null, fetcher);Fetches data only if `userId` exists; otherwise, disables the request.
const { data, error } = useSWR('/api/posts', fetcher, {
onErrorRetry: (error, key, config, revalidate, { retryCount }) => {
if (retryCount >= 3) return;
setTimeout(() => revalidate({ retryCount }), 5000);
}
});Retries failed requests up to 3 times with a 5-second delay between retries.
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'));
}Updates cached data optimistically before sending the actual request and then revalidates.
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.