DEV Community

Arhan Khan
Arhan Khan

Posted on

SWR for Beginners: Data Fetching in React Without the Boilerplate

Fetching data in React used to mean writing the same useEffect + useState + loading flag in every component. SWR, built by the Vercel team, replaces all of that with one hook — and adds caching, revalidation, and error handling for free.

The name comes from "stale-while-revalidate": SWR shows you the cached data immediately, then quietly fetches fresh data in the background and updates the UI. Your app feels instant even on a slow network.

Here is the whole idea in a few lines:

import useSWR from 'swr';

const fetcher = (url) => fetch(url).then((res) => res.json());

function UserProfile({ id }) {
  const { data, error, isLoading } = useSWR(`/api/users/${id}`, fetcher);

  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>Something went wrong.</p>;
  return <h1>{data.name}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

That is it. No manual loading state, no effect cleanup, no duplicate requests. If two components ask for the same URL, SWR makes one request and shares the result. When you switch tabs and come back, it revalidates automatically. When the network drops and returns, it retries.

SWR also gives you mutate for optimistic updates. After a user edits their profile, you can update the cached data immediately instead of waiting for a refetch:

mutate(`/api/users/${id}`, { ...data, name: 'New Name' }, false);
Enter fullscreen mode Exit fullscreen mode

SWR is for React developers who fetch data from APIs and are tired of writing the same loading and error logic everywhere. It is small, focused, and works beautifully with REST APIs and tools like Next.js. If your app mostly reads data and shows it, SWR is one of the simplest upgrades you can make.

Top comments (0)