[React] useSWR
What is SWR
The name “SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861. 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.
useSWR
Vercel created a library called SWR for Data Detching.
Overview
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>
}
Features
SWR has you covered in all aspects of speed, correctness, and stability to help you build better experiences:
- Fast page navigation
- Polling on interval
- Data dependency
- Revalidation on focus
- Revalidation on network recovery
- Local mutation (Optimistic UI)
- Smart error retry
- Pagination and scroll position recovery
- React Suspense And a lot more.
Reference
- @ KyleMo - 了解 SWR 的運作機制,How this async state manager works ?
- @ vercel -swr
- @ TkDodo's blog -React Query as a State Manager
- @ jianshu -requestIdleCallback和requestAnimationFrame详解
- @ Cloudflare - Default Cache Behavior