React Data Fetching with SWR
Fetch and cache remote data in React using the SWR library with automatic revalidation, error retry, optimistic updates, and TypeScript generics for.
Code
import useSWR from 'swr';
interface User {
id: number;
name: string;
email: string;
}
const fetcher = async (url: string): Promise<User> => {
const res = await fetch(url);
if (!res.ok) throw new Error('Fetch failed');
return res.json();
};
export function useUser(id: number) {
const { data, error, isLoading, mutate } = useSWR<User>(
`/api/users/${id}`,
fetcher,
{ revalidateOnFocus: false, dedupingInterval: 5000 },
);
return { user: data, error, isLoading, refresh: mutate };
}How the snippet works
React Data Fetching with SWR comes down to the functions fetcher and useUser.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. When the guard condition holds, Error is thrown rather than a bogus value returned.
The result comes back as an object carrying data, error, isLoading.
What to watch for
- Plan for an install step:
swris a real dependency, resolved by the package manager. - The snippet leans on
fetch— browser-only surfaces a bare Node process cannot provide. - The guard
!res.okshort-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The main signature reads export function useUser(id: number)
useUser is the public entry point; everything else in the file exists to support it.
The call returns data, error, isLoading — destructure what you need at the call site.
Statements that matter
const fetcher = async (url: string): Promise<User> => {
const res = await fetch(url);
if (!res.ok) throw new Error('Fetch failed');
return res.json();
};
return { user: data, error, isLoading, refresh: mutate };
Interactive Tools for This Topic
FAQ
- Does `useUser` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- What happens on invalid input?
- `Error` is raised at the guard (`!res.ok`), so invalid state never reaches the main logic.
- Are there third-party dependencies?
- `swr` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.