Next.jsMedium

What is SWR and how is it used with Next.js?

SWR (stale-while-revalidate) is Vercel's React hooks library for client-side data fetching. useSWR(key, fetcher) returns cached data immediately, revalidates in the background, and updates the UI, with deduplication, focus revalidation, polling and mutation helpers built in.

Core API

  • const { data, error, isLoading, isValidating, mutate } = useSWR(key, fetcher, options).
  • The key (usually the URL) identifies the cache entry. Components using the same key share data and a single request.
  • Pass null as the key to skip fetching (conditional fetching).
  • mutate() refreshes or optimistically updates the data.
  • useSWRInfinite for pagination, useSWRMutation for remote mutations.

Useful options

refreshInterval, revalidateOnFocus, revalidateOnReconnect, dedupingInterval, fallbackData, keepPreviousData.

With the App Router

  • Use it only in Client Components.
  • Seed from the server: fetch in a Server Component and pass fallbackData, or provide a fallback map through <SWRConfig> in a client provider. The page renders with data on first load and SWR keeps it fresh.
  • You can also pass an unresolved promise as the fallback value, and SWR suspends until the server resolves it.

When to choose it

Polling, dashboards, live counters and anything that must update after load. For static or per-request data, a Server Component is simpler and ships less JavaScript.

SWR vs TanStack Query

SWR is smaller and simpler. TanStack Query has richer mutation, cache and devtools features. Both work the same way with Next.js.

Code example

tsx
1// app/providers.tsx
2"use client";
3
4import { SWRConfig } from "swr";
5
6export function Providers({
7 children,
8 fallback,
9}: {
10 children: React.ReactNode;
11 fallback: Record<string, unknown>;
12}) {
13 return (
14 <SWRConfig value={{ fetcher: (url: string) => fetch(url).then((r) => r.json()), fallback }}>
15 {children}
16 </SWRConfig>
17 );
18}
19
20// app/stats/views.tsx
21"use client";
22import useSWR from "swr";
23
24export function Views({ slug }: { slug: string }) {
25 const { data } = useSWR<{ views: number }>(`/api/views/${slug}`, { refreshInterval: 10_000 });
26 return <span>{data?.views ?? 0} views</span>;
27}
28
29// app/stats/page.tsx (Server Component)
30// const initial = await getViews("intro");
31// <Providers fallback={{ "/api/views/intro": initial }}><Views slug="intro" /></Providers>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app