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