Client-Side Data Fetching with SWR and React Query
Server Components removed the excuse for fetching page data on the client, but they did not remove the need. A dashboard that must refresh while it stays open, a filter panel that reacts to a keystroke, a notification bell that ticks β none of these belong in a request that happens once on the server. The interesting question is no longer "should the client fetch" but "what happens the second time, and the third, and when two components ask for the same thing at once".
A bare useEffect plus fetch answers none of those. It has no cache, so navigating back refetches from scratch; no dedupe, so three mounted components make three requests; no revalidation, so a tab left open for an hour shows hour-old data; and no shared error state, so each component reinvents its spinner. SWR and React Query exist to supply exactly that missing layer.
Prerequisites
- !Client Components and hooks such as useEffect and useState
- !HTTP status codes and JSON responses
- !A Next.js app with at least one route handler to call
What You'll Learn
- 1Decide which data still belongs in the browser
- 2Set up a fetcher and a provider for SWR or React Query
- 3Configure stale time, dedupe intervals and revalidation triggers
- 4Add polling and optimistic updates without races
The honest split between server and client
Before reaching for a library, be clear about which half you are on. If the data is needed to paint the page β headings, article body, product details for SEO β fetch it in the Server Component so it arrives in the HTML. If the data is scoped to the signed-in user, changes while the page is open, or is only needed after an interaction, fetching it on the client is correct and there is no apology to make.
A useful test: ask what happens if JavaScript fails to load. If the answer is "the page is empty", the data probably belonged on the server. If the answer is "the page shows its content but cannot filter or refresh", you have split it correctly.
// app/dashboard/page.js β server-rendered shell, client-rendered live region
import LiveTicker from './live-ticker';
export default async function Dashboard({ searchParams }) {
const { range } = await searchParams;
const summary = await getSummary(range); // rendered into the HTML
return (
<main>
<h1>Overview</h1>
<section>{summary.kpis.map((k) => <Stat key={k.id} {...k} />)}</section>
{/* Nothing critical lives behind the fetch below */}
<LiveTicker />
</main>
);
}
Getting SWR running
SWR's name comes from stale-while-revalidate: it shows whatever it last held immediately, then goes to the network and swaps in the fresh copy. That is why SWR screens feel instant on repeat visits β you are never staring at an empty state for data you already earned.
'use client';
import useSWR from 'swr';
const fetcher = async (url) => {
const res = await fetch(url);
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
};
export default function ActivityFeed() {
const { data, error, isLoading, isValidating, mutate } = useSWR(
'/api/activity?limit=20',
fetcher,
{ revalidateOnFocus: true, keepPreviousData: true }
);
if (error) return <p role="alert">Could not load activity.</p>;
if (isLoading) return <p>Loading activityβ¦</p>;
return (
<section>
{isValidating && <span className="pulse">Refreshing</span>}
<ul>
{data.items.map((item) => (
<li key={item.id}>
<strong>{item.actor}</strong> {item.summary}
</li>
))}
</ul>
<button onClick={() => mutate()}>Refresh now</button>
</section>
);
}
The throw inside the fetcher matters. If a 403 or a 500 resolves to a JSON body, SWR treats the request as successful and your component renders undefined.x three screens later. Fail loudly at the fetcher and the error branch does its job.
The same key used by two components produces one request and one shared cache entry. That single property eliminates the most common performance bug in data-heavy React apps: a parent, a child, and a sibling each fetching the same resource on mount.
The knobs that actually change behaviour
React Query exposes more of the machinery, which makes the mental model easier to read even if you eventually ship SWR for its smaller API. Both libraries are governed by the same four questions.
| Question | SWR option | React Query option | What it changes |
|---|---|---|---|
| How long is fresh data good for? | dedupingInterval | staleTime | Whether a remount hits the network |
| When should we re-check? | revalidateOnFocus, revalidateOnReconnect | refetchOnWindowFocus, refetchOnReconnect | Behaviour when the tab regains focus |
| How long may we show old data? | keepPreviousData | placeholderData: keepPreviousData | Whether pagination jumps blank the list |
| How often do we poll? | refreshInterval | refetchInterval | Background refresh cadence |
Set staleTime to zero and every navigation refetches: correct for a live order book, wasteful for a category list. Set it to an hour and a user who edits their profile may stare at stale identity for an hour. The default most teams settle on is a few minutes for reference data, seconds for anything the user can mutate, and immediate invalidation triggered by the mutation itself rather than by a timer.
'use client';
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000,
retry: (failureCount, error) =>
error.status >= 500 && failureCount < 2,
refetchOnWindowFocus: false,
},
},
});
export function Providers({ children }) {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
}
export function RecentOrders() {
const { data, isPending, isError, refetch } = useQuery({
queryKey: ['orders', 'recent'],
queryFn: () => fetch('/api/orders?recent=1').then((r) => r.json()),
refetchInterval: 30_000,
});
if (isPending) return <Skeleton rows={5} />;
if (isError) return <button onClick={() => refetch}>Retry</button>;
return <OrderTable rows={data.orders} />;
}
Note the explicit retry predicate. Retrying a 400 is pointless and delays the error state; retrying a 502 twice with backoff usually hides a transient blip from the user entirely.
Polling, streaming, and knowing when to stop
Polling every thirty seconds is a reasonable default and a terrible assumption. It costs a request per open tab per interval, it scales linearly with users, and it still shows data up to thirty seconds late. Three upgrades exist, in increasing order of effort: back off when the tab is hidden using document.visibilityState, raise the interval for data that rarely moves, and switch to a persistent connection when latency or freshness genuinely matters.
For a notifications bell or a live collaboration surface, Server-Sent Events or a WebSocket beats polling outright, and you can still wrap the stream in the same cache by calling mutate with each incoming event. The cache stays the single source of truth for the UI while the transport underneath changes.
Optimistic updates without lying to yourself
The pattern is: snapshot the cache, apply the change locally, send the request, and either keep the change or roll back. Rollback is not optional β if the server rejects the mutation and you have already painted success, the user has been told a small lie that they will discover later.
'use client';
import useSWR from 'swr';
export function ToggleTask({ task }) {
const { data, mutate } = useSWR('/api/tasks', fetcher);
async function toggle() {
const previous = data;
const next = {
...previous,
tasks: previous.tasks.map((t) =>
t.id === task.id ? { ...t, done: !t.done } : t
),
};
// Paint immediately, then reconcile.
await mutate(
async () => {
const res = await fetch(`/api/tasks/${task.id}`, { method: 'PATCH' });
if (!res.ok) throw new Error('Save failed');
return fetch('/api/tasks').then((r) => r.json());
},
{ optimisticData: next, rollbackOnError: true, populateCache: false }
);
}
return <button onClick={toggle}>{task.done ? 'Undo' : 'Complete'}</button>;
}
populateCache: false is the subtle part: the function you pass re-fetches the canonical list rather than trusting your optimistic object, so the server's version β with whatever ids or timestamps it decided β becomes what the cache holds.
Loading, empty, and error are three different screens
A hook hands you a small state machine, and the quality of the interface depends almost entirely on whether you render every branch of it. Treating loading and error as one generic "not ready" condition is the usual shortcut, and it fails users in three separate ways: an empty list that might be loading, an error that looks like an empty list, and a spinner that persists after the data arrived.
Each branch wants a different shape. Loading wants a skeleton that matches the final layout, so the page does not jump when content lands β and it wants keepPreviousData or an equivalent when you are only refreshing something already on screen, because replacing a populated list with a spinner is a regression disguised as feedback. Empty wants its own state with a sentence explaining why it is empty and, where it makes sense, the one action that would fill it. Error wants a message that names what failed and a retry control wired to the hook's own refetch, not to a page reload.
'use client';
import useSWR from 'swr';
export function InvoiceList({ customerId }) {
const key = `/api/customers/${customerId}/invoices`;
const { data, error, isLoading, mutate } = useSWR(key, fetcher, {
keepPreviousData: true,
});
if (error) {
return (
<div role="alert">
<p>Invoices could not be loaded.</p>
<button onClick={() => mutate()}>Try again</button>
</div>
);
}
if (isLoading) return <Skeleton rows={4} />;
if (data.invoices.length === 0) {
return (
<div>
<p>No invoices yet. They appear here as soon as you send one.</p>
<a href="/invoices/new">Create the first invoice</a>
</div>
);
}
return <InvoiceTable rows={data.invoices} />;
}
The last branch is the one teams skip, and it is the one users remember: an empty state that explains itself turns a dead end into an instruction. Keep the retry inside the component rather than at page level, so a failure in one panel never blanks a dashboard that is otherwise fine.
Common Mistakes
Fetching page-level content in a client component with useEffect
Fix: Await it in the Server Component page so the HTML arrives with the data; reserve the client cache for live, user-scoped regions.
Letting a failed response resolve as success
Fix: Throw in the fetcher when res.ok is false so the error branch and retry path actually run.
Polling on a fixed interval regardless of visibility
Fix: Pause or slow the interval when document.hidden is true, and consider a push channel when freshness matters.
Awaiting mutate with no rollback strategy
Fix: Provide rollbackOnError and repopulate the cache from the server so a rejected mutation restores the previous state.
Best Practices
- Give every query a stable key built from its inputs, and nothing else
- Share one QueryClient through a provider at the root rather than per component
- Invalidate by key after a mutation instead of waiting for the next poll
- Keep a single fetcher that centralises base URLs, credentials and error mapping
Key Takeaways
- Server data paints the page; client fetching belongs to live, user-scoped or interaction-driven data.
- SWR and React Query supply cache, dedupe, revalidation and shared error state that useEffect never will.
- staleTime and its equivalents decide whether a remount hits the network β set them per data category.
- Throw on non-2xx responses in the fetcher so error UI is reachable at all.
- Optimistic updates must be able to roll back; paint first, reconcile from the server second.