React Hooks for Data Fetching
SWR is a React Hooks library for data fetching.
The name “SWR” is derived from stale-while-revalidate, a cache invalidation strategy popularized by HTTP RFC 5861.
SWR first returns the data from cache (stale), then sends the request (revalidate), and finally comes with the up-to-date data again.
With just one hook, you can significantly simplify the data fetching logic in your project. And it also covered in all aspects of speed, correctness, and stability to help you build better experiences:
...and a lot more.
With SWR, components will get a stream of data updates constantly and automatically. Thus, the UI will be always fast and reactive.
View full documentation and examples on swr.vercel.app.
import useSWR from 'swr'
function Profile() {
const { data, error, isLoading } = useSWR('/api/user', fetcher)
if (error) return
if (isLoading) return
return
}In this example, the React Hook useSWR accepts a key and a fetcher function.
The key is a unique identifier of the request, normally the URL of the API. And the fetcher accepts
key as its parameter and returns the data asynchronously.
useSWR also returns 3 values: data, isLoading and error. When the request (fetcher) is not yet finished,
data will be undefined and isLoading will be true. When we get a response, it sets data and error based on the result
of fetcher, isLoading to false and rerenders the component.
Note that fetcher can be any asynchronous function, you can use your favourite data-fetching
library to handle that part.
View full documentation and examples on swr.vercel.app.
This library is created by the team behind Next.js, with contributions from our community:
Thanks to Ryan Chen for providing the awesome swr npm package name!
The MIT License.
Focus events emit TimeoutNaNWarning with Node.js timers in jsdom
onSuccess can fire for an obsolete request after the key changes to null
Older Preload state overwrites a more recent mutated cached value
Missing export of type `SWRInfiniteMutatorOptions` starting from 2.2.5
`useSWRImmutable` ignores hook-level `refreshInterval` since 2.4.0 (regression of #4208)
Suspense mode passes an uncached promise to use(), triggering React's uncached-promise warning
Destruct "error" from useSWR throws an error
SWR re-renders the whole paginated data array when optimisticData and data functions return an array
Type error when overriding global fetcher function with null
Bug in `createCacheHelper`