SWR Cheat Sheet
Quick reference for SWR: React hooks for data fetching with stale-while-revalidate caching, automatic revalidation, and mutation patterns.
Basic Usage
| const { data, error, isLoading } = useSWR("/api/user", fetcher) | Fetch data with a key and fetcher function |
| const fetcher = (url) => fetch(url).then(r => r.json()) | Simple fetch-based fetcher function |
| if (isLoading) return <Spinner /> | Show loading state while fetching |
| if (error) return <Error /> | Handle error state from failed fetches |
| const { data } = useSWR(shouldFetch ? "/api/data" : null, fetcher) | Conditional fetching — pass null key to disable |
Configuration Options
| useSWR(key, fetcher, { revalidateOnFocus: false }) | Disable auto-revalidation when window regains focus |
| useSWR(key, fetcher, { refreshInterval: 5000 }) | Poll every 5 seconds for real-time data |
| useSWR(key, fetcher, { dedupingInterval: 2000 }) | Dedupe requests within 2 seconds |
| useSWR(key, fetcher, { fallbackData: initialData }) | Provide fallback data for SSR/SSG hydration |
| useSWR(key, fetcher, { suspense: true }) | Enable React Suspense mode for data fetching |
Mutation & Revalidation
| const { mutate } = useSWRConfig() | Get global mutate function from config |
| mutate("/api/user") | Revalidate (re-fetch) a specific key |
| mutate("/api/user", newData, false) | Update cache optimistically without revalidation |
| const { trigger } = useSWRMutation("/api/user", updateFn) | Define a remote mutation with useSWRMutation |
| mutate((key) => key.startsWith("/api/"), undefined, { revalidate: true }) | Revalidate multiple keys matching a filter |
Advanced Patterns
| useSWR(["/api/user", id], ([url, id]) => fetchWithId(url, id)) | Array key for dependent parameters |
| useSWRInfinite((i, prev) => `/api/items?page=${i+1}`, fetcher) | Infinite loading / pagination |
| const { data, size, setSize } = useSWRInfinite(...) | Control page size for infinite scroll |
| useSWR("/api/stream", fetcher, { keepPreviousData: true }) | Keep showing previous data while revalidating |
| useSWRSubscription(key, (key, { next }) => { ... }) | Subscribe to real-time data sources (WebSocket) |
Global Configuration
| <SWRConfig value={{ fetcher, revalidateOnFocus: false }}> | Wrap app with global SWR defaults |
| <SWRConfig value={{ provider: () => new Map() }}> | Custom cache provider (e.g., for testing) |
| <SWRConfig value={{ fallback: { "/api/user": userData } }}> | Pre-fill cache for SSR hydration |
| <SWRConfig value={{ onError: (err) => reportError(err) }}> | Global error handler for all SWR hooks |
| <SWRConfig value={{ onSuccess: (data) => log(data) }}> | Global success callback for all fetches |
Step-by-Step Guide
Read Guide →