← Back to React Course | Chapter 10: Data Fetching & Async | Lesson 7 of 10

Data Fetching with SWR

SWR is like a food delivery app that shows you yesterday's saved menu instantly while it quietly checks if today's menu has changed.

The Stale-While-Revalidate Idea

SWR's core idea, and its namesake, is showing cached (stale) data to the user immediately, while simultaneously firing off a fresh request in the background to revalidate it. This makes the UI feel instant even on a slow connection, updating seamlessly once the fresh data arrives.

Note: This tradeoff (briefly showing possibly-outdated data) is usually a good one for a snappier UI — SWR updates it automatically moments later.

Warning: For data that must always be perfectly fresh (like a live financial balance), the brief staleness window may not be acceptable — configure revalidation settings accordingly.

Example: The Stale-While-Revalidate Idea

markup
// Run in your local React project (npm install required)
import useSWR from 'swr';

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

function UserList() {
  const { data, error, isLoading } = useSWR('/api/users', fetcher);
  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>Failed to load</p>;
  return <ul>{data.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

The Key and Fetcher Pattern

useSWR takes two arguments: a key (usually the URL, used to identify and cache the request) and a fetcher function that actually performs the request. SWR doesn't include a built-in fetcher — you provide a small function, often just a thin wrapper around fetch().

Note: Define one shared fetcher function once and reuse it across every useSWR call in your app.

Warning: Passing null as the key tells SWR to skip fetching entirely — useful for conditional fetching, but easy to do by accident if a variable is unexpectedly null.

Example: The Key and Fetcher Pattern

markup
// Run in your local React project (npm install required)
import useSWR from 'swr';

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

function Profile({ userId }) {
  const { data } = useSWR(userId ? `/api/users/${userId}` : null, fetcher);
  return <p>{data ? data.name : 'No user selected'}</p>;
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Automatic Background Revalidation

By default, SWR automatically refetches data in situations like the browser window regaining focus or the network reconnecting, keeping data fresh without any manual refresh logic. These behaviors can be tuned via configuration options passed as a third argument.

Note: revalidateOnFocus is especially useful for dashboards that should show fresh data when a user switches back to the tab.

Warning: These automatic background refetches can cause more network requests than expected if not tuned — check SWR's config options if this becomes a concern.

Example: Automatic Background Revalidation

markup
// Run in your local React project (npm install required)
import useSWR from 'swr';

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

function LiveData() {
  const { data } = useSWR('/api/stats', fetcher, {
    revalidateOnFocus: true,
    refreshInterval: 5000,
  });
  return <p>Stat value: {data?.value}</p>;
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Common Mistakes
  1. Confusing SWR's key with a React Query query key syntax — SWR's key is usually just the URL string itself, not an array.
  2. Not understanding stale-while-revalidate — SWR intentionally shows old cached data first, then updates it, rather than always blocking on a fresh fetch.
  3. Forgetting the fetcher function isn't built in — you must provide one (often a simple fetch wrapper) yourself.
Chapter Summary
  • SWR is a lightweight data-fetching library named after the stale-while-revalidate HTTP caching strategy.
  • useSWR(key, fetcher) returns data, error, and isLoading, refetching automatically in the background.
  • The key is typically the request URL itself, used to identify and cache each request.
  • SWR shows cached (possibly stale) data immediately while silently fetching a fresh copy in the background.
Browser Support

Requires npm install swr — not available via CDN in this sandbox; works with React 16.8+.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.