SWR
lastmod 2024-02-26created 2023-12-083 edits
The name “SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861 (opens in a new tab). SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.
The name "SWR" comes from stale-while-revalidate, an HTTP cache invalidation strategy made known by HTTP RFC 5861.
SWR is a strategy that first
- returns data from the cache (stale),
- then sends a fetch request (revalidate),
- and finally brings in the up-to-date data.
Example
import useSWR from 'swr'
function Profile() {
const { data, error, isLoading } = useSWR('/api/user', fetcher)
if (error) return <div>failed to load</div>
if (isLoading) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
Usage with Next.js
See also
- react-query (TanStack Query)
- SWR (stale-while-revalidate)