Data Fetching Without the Headaches — useSWR in Next.js
Fetching data in a React application is simple. You make a request, wait for the response, and render the result.
Contents
The Problem with Data Fetching
Fetching data in a React application is simple. You make a request, wait for the response, and render the result. The problem starts when you need to do more than just fetch it.
You need to handle loading states, errors, caching, refetching, stale data, and keeping multiple components in sync. What started as a few lines of fetch() can quickly turn into a collection of useState and useEffect calls. And if the same data is needed in multiple places, you may end up making the same request multiple times.
The difficult part isn’t getting data from the server. It’s managing what happens after you get it.
What Is SWR?
SWR is a React library for fetching and managing data from a server. The name comes from stale-while-revalidate, a caching strategy where you first use the data you already have and then fetch the latest version in the background.
Instead of making the user wait for every request, SWR can show cached data immediately and update it when fresh data arrives.It also takes care of things that usually require extra code, such as caching, request deduplication, revalidation, loading states, and error handling.
In short, SWR turns server data into something your React components can work with without having to build the entire data-fetching layer yourself.
The Stale-While-Revalidate Model
The idea behind SWR is simple: use what you already have, then check for something newer.
When a request is made, SWR first looks in its cache. If cached data exists, it can be shown immediately instead of making the user wait.
At the same time, SWR sends a request to the server to check for fresh data. Once the response arrives, the cache is updated and the UI re-renders with the latest information.
This gives you the best of both worlds fast UI from cached data and fresh data from the server.
Your First useSWR
Getting started with SWR is surprisingly simple. Install the package and pass a key and a fetcher to useSWR.
npm install swrThen create a small fetcher:
const fetcher = (url: string) =>
fetch(url).then((res) => res.json());And use it in your component:
const { data, error, isLoading } = useSWR(
"/api/users",
fetcher
);That’s all you need to make your first SWR request.
The first argument, "/api/users", is the key that identifies the data. The second is the fetcher, which tells SWR how to retrieve it.
From here, SWR takes care of the caching and revalidation for you, while your component only needs to worry about displaying the data.
Understanding the SWR Response
useSWR gives you more than just the data. It returns a set of values that let you handle the different states of a request.
const {
data,
error,
isLoading,
isValidating,
} = useSWR("/api/users", fetcher);- data — The data returned by the fetcher.
- error — The error thrown if the request fails.
- isLoading — true when there is no data yet and the request is still loading.
- isValidating — true whenever SWR is fetching or revalidating data.
The difference between isLoading and isValidating is especially useful. You might already have data displayed while SWR is fetching a newer version in the background. In that case, isLoading is false, but isValidating is true.
This lets you show existing data while still giving the user feedback that it is being refreshed.
Caching & Request Deduplication
One of the main benefits of SWR is that it keeps fetched data in a shared cache.
If multiple components request the same resource:
useSWR("/api/users", fetcher);SWR can reuse the cached data instead of treating every component as a completely separate request.
This is where request deduplication becomes useful. If several components request the same key around the same time, SWR can avoid sending unnecessary duplicate requests.
The result is less unnecessary network traffic and a more consistent view of the same server data across your application.
Revalidation
Cached data is useful, but it can become stale. Revalidation is how SWR checks whether the data in its cache is still up to date.
SWR can automatically revalidate data when the user returns to the browser tab, reconnects to the network, or at a regular interval.
For example:
const { data } = useSWR(
"/api/status",
fetcher,
{
refreshInterval: 5000,
}
);Here, SWR checks for fresh data every five seconds.
You can also trigger a revalidation manually when you need to:
const { data, mutate } = useSWR(
"/api/users",
fetcher
);await mutate();The important part is that revalidation doesn’t mean throwing away the cached data and making the user wait. SWR can keep showing the existing data while it fetches the latest version in the background.
Mutating Data
Fetching data is only half of the story. Eventually, your application needs to change the data on the server.
This is where SWR’s mutation features come in. After creating, updating, or deleting something, you can update or revalidate the cached data instead of manually managing another round of state updates.
For example:
const { data, mutate } = useSWR(
"/api/users",
fetcher
);await updateUser();await mutate();After the update succeeds, mutate() tells SWR to fetch the latest data and update the cache.
SWR also supports optimistic updates, where you update the UI immediately and send the request in the background.
This makes interactions feel faster while still keeping the client and server data in sync.
SWR with Next.js
SWR works especially well with Next.js, but it doesn’t replace Next.js’s built-in data fetching.
SWR is mainly useful when client-side code needs to fetch, cache, and revalidate data.
Since useSWR is a React hook, it belongs in a Client Component:
"use client";import useSWR from "swr";For data that can be fetched on the server and doesn’t need client-side interaction, a Server Component is often the simpler choice.
Server Component
→ Fetch data on the server
→ Render the pageClient Component + SWR
→ Fetch data on the client
→ Cache it
→ Revalidate it
→ Keep it updatedSo the choice isn’t really SWR vs Next.js. They solve different parts of the problem.
Use SWR when your client needs to interact with and keep server data fresh. For simple server-rendered data, Next.js’s built-in approach may be all you need.
When Should You Use SWR?
SWR is most useful when your application has client-side data that can become stale and needs to stay in sync with the server.
Good use cases include:
- Dashboards- refresh metrics and statistics without reloading the page.
- User profiles- share and cache user data across multiple components.
- Search- fetch results as the query changes while avoiding unnecessary requests.
- Notifications- keep notification counts and lists reasonably fresh.
- CRUD applications- update cached data after creating, editing, or deleting records.
- Live-ish data- periodically revalidate information such as status or activity.
You don’t need SWR just because you’re fetching data. If a page can fetch its data on the server and doesn’t need client-side revalidation, a Server Component may be a better fit.
Use SWR when the client needs to own and keep server data fresh.
When You Don’t Need SWR
SWR is useful, but it shouldn’t be added to every project or every request. If the data is only needed to render a page and doesn’t need client-side updates, fetching it on the server is often simpler.
For example:
- Static content — blog posts, documentation, or marketing pages.
- Server-only data — data that doesn’t need to be accessed by client-side components.
- One-time requests — data that doesn’t need caching or revalidation.
- Simple pages — where a basic server-side fetch() already solves the problem.
Adding SWR in these cases can introduce another layer of complexity without providing much benefit.
The goal isn’t to use SWR everywhere. Use it when its caching and revalidation features actually solve a problem.
The Takeaway
SWR isn’t just a replacement for fetch().
Its real value is in managing server data on the client — caching it, keeping it fresh, avoiding duplicate requests, and making updates easier to handle. The API is small, but the problems it solves can become surprisingly complicated as an application grows.
If your data needs to be cached, shared, or revalidated on the client, SWR is worth considering. If it doesn’t, keep it simple.
Use SWR when you need it, not just because you can.