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 <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>
}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 (
<SWRConfig value={{ refreshInterval: 3000, fetcher: (resource, init) => fetch(resource, init).then(r => r.json()) }}>
<Dashboard />
</SWRConfig>
)
}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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
