useSWR
A lightweight, declarative way to fetch data in React
npm install swr
import useSWR from "swr"; const fetcher = url => fetch(url).then(r => r.json()); 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>; }
Revalidation is SWR’s core idea for keeping data fresh while keeping UI fast.
This gives users:
SWR revalidates when:
mutate()
Revalidation ensures the UI is:
Instead of guessing when to refetch, SWR manages it for you.
Sometimes you may want to disable automatic revalidation:
useSWR("/api/user", fetcher, { revalidateOnFocus: false, revalidateOnReconnect: false, refreshInterval: 0, });
const { mutate } = useSWR("/api/user", fetcher); // Force revalidation mutate();
useSWR(key, fetcher) returns:
useSWR(key, fetcher)
const { data, error, isLoading, isValidating, mutate } = useSWR( "https://api.github.com/users/octocat", fetcher );
if (error) return <p>Failed to load user</p>; if (isLoading) return <p>Loading…</p>; return ( <> {isValidating && <p>Updating…</p>} <div> <h2>{data.name}</h2> <p>@{data.login}</p> <p>Followers: {data.followers}</p> <button onClick={() => mutate()}>Refresh</button> </div> </> );
const { data, mutate } = useSWR("/api/user", fetcher); async function updateName(newName) { mutate({ ...data, name: newName }, false); // optimistic update await fetch("/api/user", { method: "POST", body: JSON.stringify({ name: newName }) }); mutate(); // revalidate with fresh data }