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.
Installation avec revue préalable
Cet actif nécessite une revue. Le prompt copié demande un dry-run, affiche les écritures, puis continue seulement après confirmation.
npx -y tokrepo@latest install dbec11cd-37be-11f1-9bc6-00163e2b0d79 --target codexDry-run d'abord, confirmez les écritures, puis lancez cette commande.
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.
Questions fréquentes
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.
Sources citées (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
En lien sur TokRepo
Fil de discussion
Actifs similaires
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.
v0 by Vercel — AI UI Component Generator
AI-powered tool that generates production-ready React and Next.js UI components from text descriptions. Uses shadcn/ui and Tailwind CSS. Copy-paste or install via CLI. 8,000+ stars.
Next.js AI Chatbot — Vercel Reference App Template
Production-ready AI chatbot template by Vercel using Next.js, AI SDK, shadcn/ui, and Auth.js. Supports Claude, GPT-4, and Gemini. Streaming, tool use, file uploads, and conversation history. 8,000+ stars.