Frontend Development 15 min read

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.

ByteDance ADFE Team
ByteDance ADFE Team
ByteDance ADFE Team
Understanding SWR: Stale‑While‑Revalidate Data Fetching in React

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.

frontendreactHooksSWRdata fetchingStale-While-Revalidate
ByteDance ADFE Team
Written by

ByteDance ADFE Team

Official account of ByteDance Advertising Frontend Team

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.