swr
БесплатноБез исполняемых скриптовНе проверенFetch, cache, and revalidate data in React with SWR — stale-while-revalidate data fetching library by Vercel. Use when someone asks to "fetch data in React"…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
SWR
Overview
SWR (stale-while-revalidate) is a React hooks library from Vercel for remote data: it returns cached data immediately, then revalidates in the background. It deduplicates requests, revalidates on window focus and network reconnect, retries errors with exponential backoff, and supports polling, pagination, infinite loading, mutations and optimistic UI. The current stable release is 2.5.1 (August 2026); 2.5 added an experimental cacheData option for preloading from React Server Components and an unload() function that clears the whole cache. SWR does not issue requests itself: you give it a key and a fetcher function.
Instructions
Setup
npm install swr
Basic data fetching
fetch does not throw on 4xx/5xx, so the fetcher must do it or SWR will treat an error body as data.
// lib/fetcher.ts
export class ApiError extends Error {
constructor(message: string, public status: number) {
super(message);
}
}
export const fetcher = async <T,>(url: string): Promise<T> => {
const res = await fetch(url);
if (!res.ok) throw new ApiError(`Request failed: ${res.status}`, res.status);
return res.json();
};
// hooks/useUser.ts
import useSWR from "swr";
import { fetcher } from "@/lib/fetcher";
interface User { id: string; name: string; email: string }
export function useUser(userId: string | null) {
// A null key skips the request (conditional fetching)
const { data, error, isLoading, isValidating, mutate } = useSWR<User>(
userId ? `/api/users/${userId}` : null,
fetcher,
);
return { user: data, error, isLoading, isValidating, mutate };
}
isLoading is true only while there is no data yet; isValidating is true during any request, including background revalidation. If the key is an array or object, the whole value is passed to the fetcher as one argument (it is not spread, unlike SWR 1.x).
Global configuration
// app/providers.tsx
"use client";
import { SWRConfig } from "swr";
import { fetcher } from "@/lib/fetcher";
export function Providers({ children }: { children: React.ReactNode }) {
return (
<SWRConfig
value={{
fetcher,
revalidateOnFocus: true, // default true
revalidateOnReconnect: true, // default true
dedupingInterval: 2000, // default 2000 ms
errorRetryCount: 3, // default: retry without a limit
shouldRetryOnError: (err) => !(err instanceof Error && "status" in err && err.status === 404),
}}
>
{children}
</SWRConfig>
);
}
Polling is refreshInterval: 5000 (ms) on a hook or in the config. refreshWhenHidden and refreshWhenOffline are off by default.
Mutation and optimistic updates
For a write triggered by a user action, use useSWRMutation: it sends the request only when trigger is called, shares the cache with useSWR, and supports optimisticData and rollback.
// components/TodoList.tsx
import useSWR from "swr";
import useSWRMutation from "swr/mutation";
interface Todo { id: number; title: string; done: boolean }
async function createTodo(url: string, { arg }: { arg: { title: string } }) {
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(arg),
});
if (!res.ok) throw new Error("Could not create todo");
return (await res.json()) as Todo;
}
export function TodoList() {
const { data: todos = [] } = useSWR<Todo[]>("/api/todos");
const { trigger, isMutating } = useSWRMutation("/api/todos", createTodo);
const addTodo = (title: string) =>
trigger(
{ title },
{
optimisticData: (current?: Todo[]) => [...(current ?? []), { id: -1, title, done: false }],
populateCache: (created: Todo, current?: Todo[]) => [...(current ?? []), created],
rollbackOnError: true,
revalidate: false,
},
);
// render todos and a form that calls addTodo
}
With the plain mutate(key, asyncFn, options) API the async function must return the new data. A function that returns nothing writes undefined into the cache until the revalidation finishes, so data is briefly undefined:
const { mutate } = useSWR<Todo[]>("/api/todos");
await mutate(
async (current = []) => [...current, await createTodo("/api/todos", { arg: { title } })],
{ optimisticData: (current = []) => [...current, { id: -1, title, done: false }], rollbackOnError: true },
);
mutate(key) with no data just marks the key stale and refetches it. The global mutate (from useSWRConfig() or imported from swr) accepts a filter function as key, for example to revalidate every key starting with /api/todos.
Pagination
Keep the previous page on screen while the next one loads with keepPreviousData:
import { useState } from "react";
import useSWR from "swr";
function PostList() {
const [page, setPage] = useState(1);
const { data, isLoading }
Установить swr в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл swr?
Fetch, cache, and revalidate data in React with SWR — stale-while-revalidate data fetching library by Vercel. Use when someone asks to "fetch data in React", "SWR", "data fetching hook", "cache API calls", "stale-while- revalidate", "auto-refresh data", or "React data fetching without Redux". Covers data fetching, caching, revalidation, mutation, pagination, and optimistic updates.
Как установить скилл swr?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл swr запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic