SWR
SWR
Vercel's data fetching library. stale-while-revalidate strategy.
SWR
Vercel's data fetching library. stale-while-revalidate strategy.
SWR is a data fetching library for React developed by Vercel, named after the "stale-while-revalidate" HTTP cache strategy. It first returns cached data (stale), then fetches the latest data in the background (revalidate) and updates it.
The core of SWR is the useSWR hook. It takes a key (usually an API URL) and a fetcher function, and returns the data, error, and isLoading states. Even if it is called from multiple components with the same key, the requests are automatically deduplicated.
SWR has a variety of built-in features such as automatic revalidation on focus, polling, optimistic updates, and error retry. It is also fully compatible with SSR, so data fetched on the server can be passed to the client.
Compared with TanStack Query (React Query), SWR is lighter and simpler. If you need complex caching strategies or mutation management, TanStack Query is suitable; for simple data fetching, SWR is suitable.
import useSWR, { useSWRConfig, mutate } from 'swr';
// ๊ธฐ๋ณธ fetcher ํจ์
const fetcher = (url: string) => fetch(url).then(res => res.json());
// ๊ธฐ๋ณธ ์ฌ์ฉ๋ฒ
function Profile() {
const { data, error, isLoading, isValidating } = useSWR(
'/api/user',
fetcher,
{
revalidateOnFocus: true,
revalidateOnReconnect: true,
refreshInterval: 30000, // 30์ด๋ง๋ค ์๋ ๊ฐฑ์
dedupingInterval: 2000, // 2์ด ๋ด ์ค๋ณต ์์ฒญ ๋ฐฉ์ง
}
);
if (error) return <div>์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค</div>;
if (isLoading) return <div>๋ก๋ฉ์ค...</div>;
return (
<div>
<h1>{data.name}</h1>
{isValidating && <span>์
๋ฐ์ดํธ ์ค...</span>}
</div>
);
}
// ์กฐ๊ฑด๋ถ ํ์นญ
function UserPosts({ userId }: { userId?: string }) {
// userId๊ฐ ์์ผ๋ฉด ์์ฒญ ์ ํจ
const { data } = useSWR(
userId ? `/api/users/${userId}/posts` : null,
fetcher
);
return <PostList posts={data} />;
}
// ๋๊ด์ ์
๋ฐ์ดํธ (Optimistic Update)
function TodoItem({ todo }: { todo: Todo }) {
const handleToggle = async () => {
// ์ฆ์ UI ์
๋ฐ์ดํธ
mutate(
'/api/todos',
(todos: Todo[]) =>
todos.map(t => t.id === todo.id ? { ...t, done: !t.done } : t),
{ revalidate: false }
);
// ์๋ฒ์ ์์ฒญ
await fetch(`/api/todos/${todo.id}`, {
method: 'PATCH',
body: JSON.stringify({ done: !todo.done })
});
// ์๋ฒ ๋ฐ์ดํฐ๋ก ์ฌ๊ฒ์ฆ
mutate('/api/todos');
};
return <div onClick={handleToggle}>{todo.title}</div>;
}
// useSWRMutation์ผ๋ก mutation ์ฒ๋ฆฌ
import useSWRMutation from 'swr/mutation';
async function createPost(url: string, { arg }: { arg: { title: string } }) {
return fetch(url, {
method: 'POST',
body: JSON.stringify(arg)
}).then(r => r.json());
}
function NewPost() {
const { trigger, isMutating } = useSWRMutation('/api/posts', createPost);
const handleSubmit = async (title: string) => {
await trigger({ title });
mutate('/api/posts'); // ๋ชฉ๋ก ๊ฐฑ์
};
return <button disabled={isMutating}>{isMutating ? '์ ์ฅ์ค...' : '์์ฑ'}</button>;
}
In a technical meeting:
"The dashboard is calling the same API from 5 places. With SWR, requests are deduplicated automatically, and the data is refreshed to the latest on focus. It also feels like real time."
In a technical interview:
"What is the stale-while-revalidate strategy?" - "It first shows the stale cached data, then fetches the latest data in the background and updates it. Users see content immediately, and it soon updates to the latest state."
In a code review:
"Waiting for the server response when pressing Like is slow. Use the pattern of doing an optimistic update first with mutate and rolling back if it fails. The perceived speed is completely different."
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free