Build a real-time dashboard that refreshes data whenever the user returns to the browser tab.
Create a paginated product list that fetches new items as the user scrolls without managing loading states.
Show optimistic UI updates in a form so users see their submission succeed instantly before the server responds.
Fetch data from a GraphQL API with automatic caching and retry logic on network failures.
SWR is a React library that simplifies fetching data from APIs in your components. The name comes from "stale-while-revalidate," a caching strategy where the browser immediately shows previously fetched (stale) data from cache while simultaneously fetching a fresh copy in the background. Once the fresh data arrives, the component automatically updates. This makes your UI feel instant even on slow connections. The core of SWR is a single hook called useSWR. You give it a URL (or any unique key) and a fetcher function, an async function that makes the actual network request and returns the data. The hook handles all the state management automatically, giving back three values: the data itself, an error if something went wrong, and a loading flag while the request is in progress. Beyond the basic fetch-and-cache behavior, SWR adds a collection of behaviors that improve the user experience without any extra configuration. It automatically refetches data when the user switches back to the browser tab (revalidation on focus), when the network comes back online after going offline, or on a timer interval for real-time data. It deduplicates simultaneous requests for the same key so multiple components needing the same data only trigger one network call. It supports optimistic UI updates, showing the expected result immediately before the server confirms it, and has built-in pagination helpers and smart error retrying. You would use SWR in a React application whenever you need to load data from an API and keep it reasonably fresh without managing loading states, caching, and refetching logic yourself. It works well with Next.js (built by the same Vercel team), supports server-side rendering and static site generation, works in React Native, and is compatible with any data-fetching approach, REST, GraphQL, or anything else. The library is TypeScript-written, lightweight, and installable via npm.
Generated 2026-05-18 · Model: sonnet-4-6 · Verify against the repo before relying on details.