npmswrv2.3.3
npmBeginner-friendly

swr

React data fetching with stale-while-revalidate caching — one hook for all your remote data needs with automatic revalidation.

reactdata-fetchingcachinghooksasync
The Problem

Fetching data in React requires useEffect + useState + loading/error states — repeated in every component. You also need caching, deduplication (don't fetch the same key twice), automatic refetch on focus, and cache invalidation after mutations.

Mental Model

SWR's core idea: const { data, error, isLoading } = useSWR(key, fetcher). The key is a unique string (usually the URL). The fetcher is your async function. SWR caches by key — the same key anywhere in your app shares data instantly. On focus or network reconnect, it silently revalidates in the background.

60-second start

Fetch and display data with loading state

import useSWR from 'swr';

const fetcher = (url: string) => fetch(url).then(r => r.json());

export function UserProfile({ userId }: { userId: string }) {
  const { data: user, error, isLoading } = useSWR(
    `/api/users/${userId}`,
    fetcher,
    { revalidateOnFocus: true }
  );

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;
  return <div>{user.name} — {user.email}</div>;
}

Use it when

Read-heavy React apps: dashboards, profiles, lists. When you want simple cache-first data with background refresh. When components far apart need to share server data without prop drilling.

Skip it when

Complex mutation workflows with optimistic updates and rollbacks (react-query/TanStack Query is more powerful for this). Server-side rendering where you need full control over data fetching timing.

Alternatives
react-queryMore powerful: built-in mutations, infinite queries, devtools, offline support
RTK QueryIf you're already using Redux Toolkit
Apollo ClientIf your API is GraphQL

Ready to explore the full API?

See every class, function, and relationship in an interactive graph.