日本語

How to Fetch and Cache Data with SWR in React

​​React​SWR,TypeScript,Vite

Pass useSWR a key such as a URL and a fetcher function, and the fetched data is cached per key. Components that use the same key and are displayed at the same time share a single request. When a screen is opened again, the cached data is shown first while the latest data is fetched in the background. This suits admin screens and dashboards where data from an API is shared across several components, or where a list and a count need to be updated together.

Below, using a small to-do API, I show how to fetch, cache, and update data, along with the number of requests that were actually sent.

Note

The test environment was Ubuntu 24.04 with Node.js 22.23.4. I used swr 2.5.1, react and react-dom 19.3.1, typescript 7.0.2, and vite 8.3.7. I ran tsc for type checking, then ran the app on the Vite development server. The API is a test mock built as a Vite plugin, and every request waits 600ms before responding. The browser was Chromium 153 (headless) driven by Playwright 1.63.0. Switching tabs was simulated by sending a focus event to window. I did not test server-side rendering with Next.js and the like, Suspense mode, useSWRInfinite or useSWRMutation, or the behavior when a request fails and the optimistic display rolls back.

Install SWR and prepare a fetcher function

Install SWR from npm. The peerDependencies of swr 2.5.1, the version I tested, list react as ^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0, so it works with React 19 as is.

sh
npm install swr

useSWR does not decide how data is fetched. You pass it a function that takes the key and returns the data (SWR calls this a fetcher). The official Getting Started guide shows how to write a function that wraps fetch and returns JSON.

Following the official error handling guide, this fetcher throws an error when the status code is not 2xx. The thrown error is then available in error from useSWR.

ts
// fetcher.ts
export class FetchError extends Error {
  constructor(public status: number, message: string) {
    super(message);
  }
}

export async function fetcher<T>(url: string): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) {
    const body = (await res.json()) as { message?: string };
    throw new FetchError(res.status, body.message ?? res.statusText);
  }
  return res.json() as Promise<T>;
}

Fetch a list with useSWR

This is a component that displays the list. As described in the data fetching guide, the fetcher receives the key (here '/api/todos') as its first argument. The type argument <Todo[]> sets the type of data.

tsx
// TodoList.tsx
import useSWR from 'swr';
import { fetcher } from './fetcher';
import type { Todo } from './types';

export function TodoList() {
  const { data, error, isLoading, isValidating } = useSWR<Todo[]>('/api/todos', fetcher);

  if (error) return <p>読み込みに失敗しました:{error.message}</p>;
  if (isLoading) return <p>読み込み中…</p>;

  return (
    <>
      <ul>
        {data?.map((todo) => <li key={todo.id}>{todo.title}</li>)}
      </ul>
      {isValidating && <p className="stale">最新の内容を確認中…</p>}
    </>
  );
}

types.ts contains type Todo = { id: number; title: string }.

In the test environment, the component showed "Loading…" right after opening, and the list appeared about one second later. To check the failure display, I used a separate component that reads a URL returning 500. Passing the error type as the second type argument lets you use error.status as well.

tsx
const { data, error, isLoading } = useSWR<unknown, FetchError>('/api/broken', fetcher, {
  shouldRetryOnError: false, // Turn off automatic retry on failure, for this check
});
if (error) return <p>読み込みに失敗しました({error.status}):{error.message}</p>;

The screen showed the status code (500) and the error message returned by the API, which was a Japanese message meaning "An error occurred on the server".

I explain how to use isValidating in the section "Reopening shows the cache first and then refetches" below.

Using the same key, fetching happens once

I added a component that shows the count in the header and called useSWR with the same key as the list.

tsx
// TodoCount.tsx
import useSWR from 'swr';
import { fetcher } from './fetcher';
import type { Todo } from './types';

export function TodoCount() {
  const { data } = useSWR<Todo[]>('/api/todos', fetcher);
  return <p>やること:{data ? `${data.length}件` : '…'}</p>;
}

When I placed <TodoCount /> and <TodoList /> on the same screen, only one request went to /api/todos. Both components receive the same data from the same cache. The official performance guide also states that when components with the same key render at almost the same time, only one request is made. You do not need to pass the count down from the list's parent as props. I ran this inside StrictMode, and it was still one request.

Screen showing a count component and a list component, with one API request listed below
Only one request, even with two components using the same key

The "API requests" section below the screen is a count of fetch calls that I printed for the test. It is not part of the code in this article.

Reopening shows the cache first and then refetches

I made the list collapsible with a button. After it was loaded, I closed it, then reopened it 3 seconds later. The previous list appeared immediately after opening, and at the same time a second request went to /api/todos. Because the list stayed visible while "Checking for the latest content…" was shown, isLoading stayed false and isValidating was true.

Screen showing two items in the list, with "Checking for the latest content…" in gray below
Right after reopening. The cached list is shown while the data is refetched in the background

The name SWR comes from HTTP's stale-while-revalidate (SWR README on npm). The README describes returning the cached data (stale) first, then sending a request (revalidate) and replacing it with the latest data. The screen above shows that process partway through.

The official "Understanding SWR" page explains that isValidating is true whenever a request is in progress, whether or not data exists, and that isLoading is true only when a request is in progress and there is no data to display yet. A practical pattern: during the first load, check isLoading and show only "Loading…"; during a background refetch, check isValidating and show "Checking for the latest content…" in gray text below the list. This keeps the list visible while the refetch runs.

On the other hand, when I reopened the list 0.3 seconds after closing it (about 1.4 seconds after the previous request), no new request was sent. As noted on the API page, requests with the same key are treated as duplicates and not sent during dedupingInterval, which defaults to 2000ms.

Stop refetching when returning to the tab

SWR also refetches data when the window regains focus (revalidation page). In the source of swr 2.5.1, I found that it listens for the focus event on window and the visibilitychange event on document.

In the test environment, about 5 seconds after loading, I sent a focus event to window. One more request went to /api/todos, and "Checking for the latest content…" was shown while it ran.

For screens where refetching is unnecessary, set revalidateOnFocus to false. Wrapping components in SWRConfig applies the setting to every useSWR inside it (global configuration page).

tsx
import { SWRConfig } from 'swr';

<SWRConfig value={{ revalidateOnFocus: false }}>
  <TodoList />
</SWRConfig>

With this setting, sending the same focus event produced no request.

Refetch the list after adding data

After adding data through the API, the cached list becomes stale. Calling the mutate returned by useSWR with no arguments refetches the data for that key (mutation and revalidation page).

tsx
// AddTodo.tsx
import { useState } from 'react';
import useSWR from 'swr';
import { fetcher } from './fetcher';
import type { Todo } from './types';
import { postTodo } from './postTodo';

export function AddTodo() {
  const { data, mutate } = useSWR<Todo[]>('/api/todos', fetcher);
  const [title, setTitle] = useState('');

  const add = async () => {
    await postTodo(title);
    setTitle('');
    await mutate(); // Refetch the list
  };

  return (
    <div>
      <input value={title} onChange={(e) => setTitle(e.target.value)} aria-label="やること" />
      <button onClick={add} disabled={!title || !data}>追加</button>
    </div>
  );
}

postTodo is a function that sends { title } with POST to /api/todos and returns the added Todo.

When I added "Take out the trash", a GET /api/todos followed the completed POST. When that response arrived, the list grew to three items. The count component, which uses the same key, also changed to "3 items" at the same time. During the refetch, the list still showed the previous two items with "Checking for the latest content…" displayed.

mutate can also be called from another component with a key, by taking it out of useSWRConfig. However, the official documentation says that if you call it with only a key, neither the cache update nor the refetch happens unless a useSWR for that key is mounted.

Show the added item before the save completes

With the approach in the previous section, the added item appears only after two round trips: POST and then GET. Passing the data you want to display as optimisticData to mutate lets you rewrite the cache before the save completes.

tsx
// AddTodoOptimistic.tsx (add handler only)
const add = async () => {
  const current = data ?? [];
  setTitle('');
  await mutate(
    async () => [...current, await postTodo(title)],
    {
      optimisticData: [...current, { id: -1, title: `${title}(送信中)` }],
      rollbackOnError: true,
      revalidate: false,
    },
  );
};

The array returned by the function passed as the first argument to mutate becomes the cache after the save. Because revalidate: false is set, no GET is sent afterward. According to the mutate options reference, rollbackOnError restores the cache when the save fails. Its default is also true.

Right after the button was pressed, "Take out the trash (sending)" appeared at the end of the list, and the count changed to 3. About 0.7 seconds later, when the POST response arrived, the entry was replaced with "Take out the trash". During this period, only one request, the POST, was sent. No GET for the list was sent.

Screen showing the count at 3 and "Take out the trash (sending)" at the end of the list
Right after pressing Add. The list and count change without waiting for the save to complete

Do not fetch until the conditions are met

Sometimes a key requires a value that is not yet available, such as when fetching the information for a selected user. If you pass null as the key, SWR does not send a request (conditional fetching page).

tsx
// UserName.tsx
import useSWR from 'swr';
import { fetcher } from './fetcher';
import type { User } from './types';

export function UserName({ userId }: { userId: number | null }) {
  const { data, isLoading } = useSWR<User>(
    userId === null ? null : `/api/users/${userId}`,
    fetcher,
  );
  if (userId === null) return <p>ユーザーを選んでください</p>;
  if (isLoading) return <p>読み込み中…</p>;
  return <p>名前:{data?.name}</p>;
}

In the test environment, there were zero requests until a user was selected. Pressing the button for user 1 fetched /api/users/1, and pressing the button for user 2 fetched /api/users/2. When I pressed the button for user 1 again, the name of user 1 appeared immediately without a loading message. Because less than 2 seconds had passed since the last fetch, no new request was sent either.

Point

The SWR cache is separated by key. Using the same key wherever the same data is used, and different keys for different data, is the foundation for both sharing and updating data.

​Posted by 86