How to Fetch Data with SWR in React

Introduction

SWR (stale-while-revalidate) is a React Hooks library for remote data fetching. It handles caching, revalidation, focus tracking, and error recovery automatically.

Step 1: Install SWR

npm install swr

Step 2: Create a Typed Fetcher

async function fetcher<T>(url: string): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) throw new Error("Fetch failed");
  return res.json();
}

Step 3: Use the useSWR Hook

interface User { id: number; name: string; email: string; }

function UserProfile({ id }: { id: number }) {
  const { data, error, isLoading } = useSWR<User>(
    `/api/users/${id}`,
    fetcher,
    { revalidateOnFocus: false, dedupingInterval: 5000 }
  );

  if (isLoading) return <Spinner />;
  if (error) return <Error message={error.message} />;
  return <div>{data?.name}</div>;
}

Advanced: Mutation and Optimistic Updates

const { mutate } = useSWR<User>(`/api/users/${id}`, fetcher);

const updateName = async (newName: string) => {
  await mutate(
    fetch(`/api/users/${id}`, {
      method: "PATCH",
      body: JSON.stringify({ name: newName }),
    }).then((r) => r.json()),
    { optimisticData: { ...data, name: newName } }
  );
};

Conclusion

SWR provides a powerful, minimal API for data fetching in React. Its caching and revalidation strategies work great for most CRUD applications without requiring a full state management library.