NextJs — API Fetching with SWR
SWR is a React hook library for data fetching. It handles caching, revalidation, focus tracking, and more automatically.
import useSWR from 'swr';
const fetcher = (url) => fetch(url).then(res => res.json());
export default function Profile() {
const { data, error } = useSWR('/api/user', fetcher);
if (error) return <div>Failed to load</div>;
if (!data) return <div>Loading...</div>;
return <div>Hello {data.name}</div>;
}