← Back to archive

Repo of the Day

vercel/swr

Published: Feb 28, 2023

Open repository ↗

React Hooks for Data Fetching - would like to implement something like this for work to reduce boilerplate on api requests. Similar to react query, but with less of a caching mechanism I think.

Summary

SWR is a React Hooks library for remote data fetching, written in TypeScript and published under the MIT license. It is named after the HTTP "stale-while-revalidate" strategy from RFC 5861: the hook first returns any cached data, then triggers a fresh request and updates the component with the new result.

What it is useful for

SWR centralizes the recurring pieces of data fetching in React — a shared cache, request deduplication, and automatic re-fetching — behind a single hook call. According to the README, it handles revalidation when the window regains focus, revalidation on network recovery, polling, pagination with scroll position recovery, optimistic UI for local mutations, and built-in retry on error. The fetcher argument is transport agnostic, so the same hook can call REST endpoints, GraphQL, or any other async source, and the README states it works in browser apps, Next.js (SSR/SSG), and React Native, with support for React Suspense.

This is most useful when several components depend on the same resource (so deduplication and the shared cache actually pay off), when on-screen data needs to stay reasonably fresh while the user navigates, or when a team wants to replace hand-written loading, error, and cache state in every component.

How engineers can use it

The README's quick start shows the smallest possible usage: pass a key (typically the API path) and a fetcher, then destructure data, error, and isLoading from the hook's return value.

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>
}

Because the key is the cache identity, two components that call useSWR('/api/user', fetcher) will share a single in-flight request. The README does not include an explicit install command, so installation and provider setup, plus the rest of the API surface (global configuration, the mutate function, the Suspense variants), live on the project's documentation site (swr.vercel.app) and the npm page for the swr package — the README only confirms the package name, the TypeScript types, and the basic API shape above.