Understanding SWR: Stale‑While‑Revalidate Data Fetching in React
This article explains the SWR library—a lightweight React hook that implements the stale‑while‑revalidate caching strategy—covering its core concepts, basic usage, advanced features like global configuration and middleware, and an overview of its internal implementation.
SWR is a React data fetching library created by the same team behind Next.js, implementing the stale‑while‑revalidate caching strategy from HTTP Cache‑Control.
The library returns cached (stale) data immediately while revalidating in the background, supports conditional requests, request deduplication, automatic revalidation on focus or network reconnection, polling, pagination, and global state sharing.
Basic usage involves calling useSWR(key, fetcher, options) , where key identifies the request and can be a string, array, function, or null. The hook returns data , error , isValidating , and mutate for cache updates.
import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
if (error) return
failed to load
if (!data) return
loading...
return
hello {data.name}!
}Advanced features such as global configuration are provided via SWRConfig , and middleware can be composed to extend hook behavior.
import useSWR, { SWRConfig } from 'swr'
function App() {
return (
fetch(resource, init).then(r => r.json()) }}>
)
}The internal implementation uses a combination of React state, a global weak‑map cache, subscription mechanisms, and a compose‑style middleware pipeline to achieve efficient, consistent data fetching across components.
ByteDance ADFE Team
Official account of ByteDance Advertising Frontend Team
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.