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.
先审查再安装
这个资产需要先审查。复制的指令会要求 Agent dry-run、列出写入项,确认后再继续。
npx -y tokrepo@latest install dbec11cd-37be-11f1-9bc6-00163e2b0d79 --target codex先 dry-run,确认写入项后再运行此命令。
What it is
SWR is a lightweight React data-fetching library created by Vercel. It implements the stale-while-revalidate caching strategy: return cached (stale) data instantly, then fetch fresh data in the background, and update the UI when the new data arrives. This delivers a responsive user experience with minimal loading states.
SWR targets React and Next.js developers who need to fetch remote data with smart caching, automatic revalidation on focus/reconnect, pagination, and optimistic updates -- all without a heavy state management library.
How it saves time or tokens
Without SWR, managing server state in React requires useEffect + useState boilerplate, manual cache invalidation, loading/error state tracking, and deduplication of concurrent requests. SWR handles all of this in a single hook call. The useSWR hook returns data, error, and isLoading with zero configuration.
How to use
- Install SWR:
npm install swr. - Define a fetcher function (e.g.,
(url) => fetch(url).then(r => r.json())). - Use
useSWR(key, fetcher)in any component to fetch and cache data.
Example
import useSWR from 'swr';
const fetcher = (url: string) => fetch(url).then(r => r.json());
function Profile() {
const { data, error, isLoading, mutate } = useSWR('/api/user', fetcher);
if (isLoading) return <span>Loading...</span>;
if (error) return <span>Failed to load</span>;
return (
<div>
<h1>{data.name}</h1>
<button onClick={() => mutate()}>Refresh</button>
</div>
);
}
Related on TokRepo
- Coding Tools -- Frontend developer libraries
- Automation Tools -- Build and development tools
Common pitfalls
- Not wrapping the app in
SWRConfigfor global configuration. Without it, you repeat fetcher and options in everyuseSWRcall. - Using SWR for client-side-only data that does not need server revalidation. For local UI state, use useState or a state manager instead.
- Forgetting that SWR deduplicates requests by key. If two components use the same key, only one fetch fires. This is a feature, but can confuse when debugging.
常见问题
It is a caching strategy where the cached (stale) data is returned immediately to render the UI, while a background request fetches fresh data. When the fresh data arrives, the UI updates. This eliminates loading spinners for repeat visits while keeping data fresh.
SWR is a client-side hook and runs in Client Components. For Server Components in Next.js App Router, use the native fetch with caching. SWR is best for interactive client-side data that needs revalidation, mutations, and optimistic updates.
SWR provides `useSWRInfinite` for paginated and infinite scroll patterns. It manages an array of page keys and fetches them incrementally. You control when to load the next page with a `getKey` function that returns the next page URL.
Yes. Use `mutate(key, newData, false)` to update the cache immediately (optimistically) before the server responds. If the server request fails, SWR rolls back to the previous data. This makes the UI feel instant for mutations.
Both solve the same problem. SWR is lighter and more opinionated, with a simpler API for common cases. TanStack Query provides more features (query invalidation groups, devtools, mutations with built-in retry). Choose SWR for simplicity; choose TanStack Query for complex data-fetching requirements.
引用来源 (3)
- SWR GitHub— SWR implements stale-while-revalidate caching for React
- SWR Documentation— Created by Vercel with built-in focus revalidation and deduplication
- SWR Pagination Docs— useSWRInfinite for pagination and infinite scroll patterns
讨论
相关资产
Nivo — Rich Data Visualization Components for React
A data visualization library built on D3 and React that provides ready-made, themeable chart components with server-side rendering support.
Relay — Declarative GraphQL Data Fetching for React
Relay is a JavaScript framework by Meta for building data-driven React applications powered by GraphQL. It handles data fetching, caching, and optimistic updates with a compiler-driven approach.
Wagmi — Reactive Primitives for Ethereum Apps
Wagmi is a collection of React hooks and Vue composables for connecting wallets, reading chain data, and writing transactions in Ethereum DApps. Built on top of Viem, it handles wallet connection, chain switching, caching, and request deduplication. Wagmi has become the standard React integration layer for modern Ethereum frontends.
Gatsby — React-Based Framework for Performant Static Sites
Gatsby is a React-based open-source framework for building fast, secure websites and apps. It combines static site generation with dynamic capabilities, pulling data from any source via GraphQL.