How-To Guide

How to Fetch Data with SWR in React

Use SWR in React for cached, type-safe data fetching with revalidation, pagination, optimistic updates, retries, and tests that do not depend on the network.

On this page

  1. Introduction
  2. Install and configure a shared fetcher
  3. Use stable cache keys
  4. Handle loading, error, and empty states
  5. Revalidation, retries, and polling
  6. Mutations and optimistic updates
  7. Pagination with useSWRInfinite
  8. Prefetching and server-rendered fallback data
  9. Testing without a real network
  10. Common pitfalls
  11. Conclusion

Introduction

Remote data in a React application is rarely a single request followed by a static render. Users navigate between pages, return to a tab minutes later, retry after a flaky network, and edit data that other views already display. SWR is a hooks library built around one idea: show cached data immediately, then revalidate it in the background. The name comes from HTTP cache semantics, “stale-while-revalidate”, but the library also handles request deduplication, focus and reconnect revalidation, retries, pagination, and optimistic mutations.

SWR is not a complete state manager. It does not own form state, local UI state, or a normalized entity store. Its contract is a cache key and a fetcher. That small surface is an advantage when the data layer is mostly reads with occasional mutations, and a limitation when the application needs complex normalized updates. This tutorial builds a typed data layer, covers the options that matter in production, and shows how to test it without hitting a real API.

Install and configure a shared fetcher

Install the library and, if you use TypeScript, keep it in dependencies because the fetcher runs in the browser:

npm install swr

A single fetcher should reject non-2xx responses, set an explicit Accept header, and centralize error construction. The generic type parameter describes what the caller expects, but TypeScript does not validate JSON at runtime:

export class HttpError extends Error {
  constructor(public readonly status: number, message: string) {
    super(message);
    this.name = 'HttpError';
  }
}

export async function fetcher<T>(url: string): Promise<T> {
  const response = await fetch(url, {
    headers: { accept: 'application/json' },
  });

  if (!response.ok) {
    throw new HttpError(response.status, `Request failed with ${response.status}`);
  }

  return (await response.json()) as T;
}

The cast is a promise to the compiler, not a guarantee about the server. Treat API responses as untrusted input at the boundary. If the endpoint is outside your control, parse the JSON with a schema library such as Zod and return the parsed value. That converts a malformed response into an error at the boundary instead of a crash several components later.

Provide the fetcher once through SWRConfig so individual hooks do not repeat it:

import { SWRConfig } from 'swr';

export function DataProvider({ children }: { children: React.ReactNode }) {
  return (
    <SWRConfig value={{ fetcher, shouldRetryOnError: true }}>
      {children}
    </SWRConfig>
  );
}

Define the fetcher outside a component, or memoize it. An inline function is a new reference on every render, which makes the data layer harder to reason about and can cause unnecessary work in effects that depend on it.

Use stable cache keys

The first argument to useSWR is the cache key. A string is the common case, but an array is useful when parameters form a query:

const key = ['/api/users', { page, status }] as const;
const { data, error, isLoading } = useSWR<UserPage>(key, ([url, params]) => {
  const query = new URLSearchParams({
    page: String(params.page),
    status: params.status,
  });
  return fetcher<UserPage>(`${url}?${query}`);
});

SWR serializes array keys deterministically, so ['/api/users', { page: 1 }] and the same values in a different property order share a cache entry when the structure is stable. Do not build keys with JSON.stringify inside the render path and then change property order; use primitives or a stable serializer.

Conditional requests are expressed with a null key. This keeps the hook mounted, which respects the rules of hooks, while telling SWR there is nothing to fetch:

const { data } = useSWR<User>(
  userId ? `/api/users/${userId}` : null,
  fetcher
);

Every key is a global cache identity. Two components that request the same key share one deduplicated request and one cache entry. That is usually desirable, but it means keys must include every variable that changes the response, such as locale, tenant, filters, and pagination. A missing tenant identifier in the key can leak one tenant’s cached data into another tenant’s view.

Handle loading, error, and empty states

SWR exposes data, error, isLoading, and isValidating. They answer different questions. isLoading is true when there is no cached data and a request is in flight. isValidating is true whenever a revalidation is running, including background refreshes with cached data on screen. An empty array or null is a successful response, not an error:

function UserList() {
  const { data, error, isLoading, isValidating, mutate } = useSWR<User[]>(
    '/api/users',
    fetcher
  );

  if (isLoading) return <Skeleton rows={3} />;
  if (error) {
    return (
      <div role="alert">
        Could not load users.
        <button onClick={() => mutate()}>Retry</button>
      </div>
    );
  }
  if (!data || data.length === 0) return <EmptyState />;

  return (
    <>
      {isValidating && <span aria-live="polite">Refreshing…</span>}
      <ul>{data.map((user) => <li key={user.id}>{user.name}</li>)}</ul>
    </>
  );
}

Do not render an error state for a background revalidation failure when cached data is still usable. A common pattern is to show a non-blocking banner while keeping the last good data visible. Conversely, do not hide a first-load error behind an empty state; users need to know the difference between “no records” and “the request failed”.

Revalidation, retries, and polling

SWR revalidates on mount, on window focus, and on network reconnect by default. These defaults make stale data fresh without user action, but they can produce surprising request volume. Tune them per resource rather than disabling them globally:

const { data } = useSWR<Dashboard>('/api/dashboard', fetcher, {
  revalidateOnFocus: false,
  refreshInterval: 30_000,
  dedupingInterval: 10_000,
});

dedupingInterval collapses identical requests within the window. refreshInterval is appropriate for dashboards and queues, not for a user profile that changes rarely. revalidateOnReconnect is useful for mobile clients that lose connectivity.

Retries need a bound and a backoff. SWR’s default retry behavior is intentionally simple; override onErrorRetry to stop on client errors and to cap the delay:

const options = {
  onErrorRetry: (
    error: HttpError,
    _key: string,
    _config: unknown,
    revalidate: (opts: { retryCount: number }) => void,
    { retryCount }: { retryCount: number }
  ) => {
    if (error.status >= 400 && error.status < 500) return;
    if (retryCount >= 5) return;
    const delay = Math.min(1_000 * 2 ** retryCount, 30_000);
    setTimeout(() => revalidate({ retryCount }), delay);
  },
};

Retrying a 401 or 404 five times wastes time and can amplify load during an outage. Retry idempotent GET requests on network errors and 5xx responses, and surface a manual retry control for everything else.

Mutations and optimistic updates

mutate updates the cache and optionally revalidates. For a mutation that should feel instant, provide optimisticData; if the request fails, rollbackOnError restores the previous cache value:

function useRenameUser(id: number) {
  const { data, mutate } = useSWR<User>(`/api/users/${id}`, fetcher);

  async function rename(name: string) {
    const next = { ...data!, name };
    await mutate(
      async () => {
        const response = await fetch(`/api/users/${id}`, {
          method: 'PATCH',
          headers: { 'content-type': 'application/json' },
          body: JSON.stringify({ name }),
        });
        if (!response.ok) throw new HttpError(response.status, 'Rename failed');
        return (await response.json()) as User;
      },
      {
        optimisticData: next,
        rollbackOnError: true,
        populateCache: true,
        revalidate: false,
      }
    );
  }

  return { user: data, rename };
}

populateCache writes the mutation result into the cache so other components using the same key update immediately. revalidate: false skips an extra request when the server response is already authoritative. If the server computes derived fields that the client cannot predict, leave revalidation enabled or update those keys explicitly.

For lists, optimistic updates are more complicated because the changed entity may appear in several cached pages. Update each affected key or revalidate the list after the mutation. Do not mutate an array in place; create a new array so React and SWR observe a new reference.

Pagination with useSWRInfinite

useSWRInfinite models a sequence of pages. getKey receives the page index and the previous page’s data, and returns null when there are no more pages:

import useSWRInfinite from 'swr/infinite';

type Page = { items: User[]; nextCursor: string | null };

function useUsers() {
  const getKey = (index: number, previous: Page | null) => {
    if (previous && previous.nextCursor === null) return null;
    const cursor = index === 0 ? '' : previous?.nextCursor ?? '';
    return `/api/users?cursor=${encodeURIComponent(cursor)}`;
  };

  const { data, size, setSize, isValidating, error } = useSWRInfinite<Page>(
    getKey,
    fetcher
  );

  return {
    users: data?.flatMap((page) => page.items) ?? [],
    loadMore: () => setSize(size + 1),
    isLoadingMore: isValidating,
    error,
  };
}

Cursor pagination is usually safer than page numbers for changing datasets. A page number can skip or duplicate rows when records are inserted between requests. Deduplicate by entity id after flattening if the API cannot guarantee a stable cursor.

Prefetching and server-rendered fallback data

SWR exposes preload for warming a key before navigation, such as on link hover. Server-rendered frameworks can pass initial data as fallback so the first paint contains content and SWR revalidates afterward:

<SWRConfig value={{ fallback: { '/api/users': initialUsers }, fetcher }}>
  <UserList />
</SWRConfig>

The fallback is a cache seed, not a security boundary. Do not serialize secrets or another user’s private data into the HTML payload. In a server-rendered app, create a fresh cache per request; a module-level cache shared across requests can leak data between users.

Testing without a real network

Mock Service Worker (MSW) intercepts fetch at the network boundary, so tests exercise the real SWR behavior without a live server:

import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';
import { renderHook, waitFor } from '@testing-library/react';
import { SWRConfig } from 'swr';

const server = setupServer(
  http.get('/api/users', () => HttpResponse.json([{ id: 1, name: 'Ada' }]))
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

const wrapper = ({ children }: { children: React.ReactNode }) => (
  <SWRConfig value={{ fetcher, provider: () => new Map() }}>{children}</SWRConfig>
);

test('loads users', async () => {
  const { result } = renderHook(() => useSWR<User[]>('/api/users', fetcher), { wrapper });
  await waitFor(() => expect(result.current.data).toHaveLength(1));
});

Create a new cache provider per test. A shared global cache makes tests order-dependent because data from one test is still present in the next. Add cases for a 500 response, an empty list, and a retry, not only the success path.

Common pitfalls

  • Unstable fetcher identity. Define the fetcher outside the component or wrap it in useCallback.
  • Keys that omit variables. Tenant, locale, filters, and pagination must be part of the key.
  • Using isValidating as the initial loading flag. It is true during background refreshes; use isLoading for first-load states.
  • Retrying non-idempotent requests. A failed POST may already have succeeded on the server. Use idempotency keys before retrying writes.
  • Global cache in SSR. Share a cache only within one request.
  • Trusting generic types. as T does not validate JSON at runtime.

Conclusion

SWR works best when the data layer is explicit: one validated fetcher, stable keys that include every input, deliberate revalidation settings, and mutations that either roll back or revalidate. The library removes a large amount of request-management code, but it does not remove the need to model failure, empty data, and cache ownership. Start with the defaults, measure request volume, and tune only the resources that need it.

Sources: SWR documentation, React rules of hooks, MSW documentation.

FAQ

When should I use SWR instead of React Query?
SWR is a good fit when you want a small data-fetching layer built around cache keys and revalidation and do not need React Query's broader mutation, infinite-query, and devtools ecosystem. Both are valid; choose one per project instead of mixing them.
Why does SWR refetch when I switch browser tabs?
SWR revalidates on focus by default to keep stale data fresh. Disable revalidateOnFocus or increase focusThrottleInterval if the request is expensive, and use refreshInterval only for data that genuinely needs polling.
How do I stop a SWR request?
Change the key to null. SWR does not fetch for a null key, which is the supported way to express a conditional request. Avoid mounting the hook conditionally, because that breaks the rules of hooks.

Related Examples

Interactive Tools for This Topic