Scripts2026年4月14日·1 分钟阅读

SWR — React Hooks for Data Fetching by Vercel

SWR is a lightweight React data-fetching library that delivers a responsive UX with built-in caching, revalidation, focus tracking, and pagination. Created by Vercel, it powers Next.js apps and any React project that needs stale-while-revalidate semantics.

Introduction

SWR stands for stale-while-revalidate — a caching strategy from HTTP RFC 5861. Return the cached data immediately, then silently fetch fresh data in the background and update the UI. Created by Vercel (the Next.js team), it pairs beautifully with server components and edge runtimes.

With over 32,000 GitHub stars, SWR is the go-to data fetching hook for React projects that want a minimal API with powerful features: automatic revalidation, focus tracking, pagination, and optimistic updates.

What SWR Does

useSWR(key, fetcher) returns { data, error, isLoading, isValidating, mutate }. Under the hood, SWR deduplicates requests (same key = one fetch), caches results in memory, revalidates on focus/reconnect/interval, and triggers re-renders when cache updates.

Architecture Overview

component calls useSWR("/api/x", fetcher)
        |
   [Cache]  hit? return data immediately
        |
   [Fetcher]  run in background
        |
   [Dedupe] same key requested elsewhere -> shared promise
        |
   [Update cache] -> re-render all subscribers
        |
   [Revalidators]
   focus, reconnect, interval, visibilitychange

Self-Hosting & Configuration

import useSWR, { SWRConfig, mutate } from "swr";

<SWRConfig value={{
  fetcher: (url) => fetch(url).then(r => r.json()),
  revalidateOnFocus: true,
  revalidateOnReconnect: true,
  refreshInterval: 30_000,
  dedupingInterval: 2_000,
  errorRetryCount: 3,
  onError: (err) => console.error("swr error", err),
}}>
  <App />
</SWRConfig>

// Optimistic updates
await mutate("/api/todos", optimisticData, { optimisticData, rollbackOnError: true });

// Infinite scroll
import useSWRInfinite from "swr/infinite";
const { data, size, setSize } = useSWRInfinite(
  (index) => `/api/posts?page=${index + 1}`,
  fetcher,
);

Key Features

  • Stale-while-revalidate — instant UI from cache + background refresh
  • Auto revalidation — on window focus, network reconnect, interval
  • Deduplication — identical requests share a single in-flight promise
  • Mutate API — manual revalidation + optimistic updates + rollback
  • PaginationuseSWRInfinite for scroll/next-page patterns
  • Suspense — opt-in Suspense mode for concurrent React
  • SSR/SSG friendly — pass initial data via fallback prop
  • TypeScript — full generics for data/error types

Comparison with Similar Tools

Feature SWR TanStack Query Apollo Client RTK Query urql
Protocol Any fetch Any fetch GraphQL Any fetch GraphQL
Bundle size ~4KB ~13KB Large Part of RTK Small
Mutations Via mutate First-class First-class First-class First-class
DevTools No Excellent Excellent Redux DevTools Excellent
Learning Curve Very Low Low-Moderate High Moderate Moderate
Best For Simple caching Complex apps GraphQL Redux shops GraphQL (small)

FAQ

Q: SWR vs TanStack Query — which should I pick? A: SWR has a tiny API and bundle. TanStack Query (formerly React Query) has richer mutation/offline features and DevTools. If you already use Vercel/Next, SWR is the path of least friction.

Q: Does SWR work with GraphQL? A: Yes, use any fetcher including graphql-request or urql's core. SWR is transport-agnostic.

Q: How do I invalidate many keys at once? A: mutate((key) => typeof key === "string" && key.startsWith("/api/todos")) — pass a filter function to bulk revalidate.

Q: Does SWR work outside React? A: The core logic is React-specific, but Vue has a separate swrv library based on the same idea.

Sources

讨论

登录后参与讨论。
还没有评论,来写第一条吧。

相关资产