SWR
React data-fetching hooks with cache keys, stale-while-revalidate updates, pagination, and optimistic mutations for client applications.
Official Documentation ↗SWR 2.x with React 18/19; server-rendered fallback needs a per-request cache. Check the official docs for the latest API surface.Installation
npm install swrpnpm add swryarn add swrMethods
No methods match this filter.
SWR is a React hooks library for remote data. A cache key and a fetcher are the contract; the library handles deduplication, revalidation, retries, pagination, and mutations. It is not a general state manager.
Key design
The key is the cache identity. Include every variable that changes the response, including tenant, locale, filters, and pagination. Use null for conditional requests. A key that omits a variable can serve one tenant’s data to another.
Loading and errors
isLoading means there is no cached data and a request is in flight; isValidating also includes background refreshes. A successful empty list is not an error. Render those states separately so users can distinguish “no data” from “the request failed”.
FAQ
- Is SWR a complete state manager?
- No. It manages remote data by cache key. Forms, local UI state, and normalized entity stores need other tools or patterns.
- Why does my request fire twice?
- SWR revalidates on mount and focus by default and deduplicates identical keys within dedupingInterval. Check the key, the fetcher identity, and the configured revalidation options.
- How do I fetch conditionally?
- Pass null as the key. Do not conditionally call the hook; hooks must run in the same order on every render.
Report a problem with this API docOpens a pre-filled issue on GitHub.