SWR

SWR

React Hooks for data fetching by Vercel

Features

  • Stale-while-revalidate caching strategy
  • Automatic revalidation on focus, reconnect, and interval
  • Built-in deduplication of concurrent requests
  • Optimistic UI updates and mutation support
  • TypeScript-first with full type inference

Pros

  • Dead simple API โ€” one hook for most use cases
  • Smart defaults that handle caching, deduplication, and revalidation
  • Tiny bundle size (~4kb gzipped)

Cons

  • Less powerful than TanStack Query for complex caching scenarios
  • No built-in devtools (community solutions exist)
  • Mutation API is simpler but less structured than alternatives

Overview

SWR is a React Hooks library for data fetching created by Vercel. Named after the HTTP cache invalidation strategy โ€œstale-while-revalidate,โ€ it returns cached data first (stale), then sends a fetch request (revalidate), and finally updates with fresh data. This pattern gives users an instant UI while ensuring data stays up to date.

SWR handles the complex parts of remote data management automatically: request deduplication, revalidation on window focus, retry on error, pagination, and more. Its minimal API (useSWR) accepts a key and a fetcher function, making it straightforward to add smart data fetching to any React component without boilerplate.

When to Use

SWR is the right choice when you need simple, effective data fetching in React with smart caching defaults, when your data fetching needs are straightforward, or when you want a lightweight alternative to TanStack Query that covers the common cases with less API surface.

Getting Started

npm install swr
import useSWR from "swr";

const fetcher = (url: string) => fetch(url).then((res) => res.json());

function Profile() {
  const { data, error, isLoading } = useSWR<{ name: string }>(
    "/api/user",
    fetcher,
  );

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Failed to load</div>;
  return <div>Hello, {data?.name}!</div>;
}