Client Fetching
Overview
While server fetching is preferred, you sometimes need to fetch data on the client (e.g., pagination, infinite scrolling, or highly user-specific live data). For this, Next.js recommends using data fetching libraries like SWR or React Query.
Syntax
'use client';
import useSWR from 'swr';
const fetcher = (url: string) => fetch(url).then((res) => res.json());
export default function Profile() {
const { data, error, isLoading } = useSWR('/api/user', fetcher);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error loading data.</div>;
return <div>Hello, {data.name}!</div>;
}Common Pitfalls
Using raw
useEffectandfetchfor client fetching, leading to race conditions, missing caching, and poor error handling.Fetching data on the client that could easily be fetched securely on the server.
Interview Questions
Why does Vercel recommend SWR or React Query for client-side fetching instead of useEffect?
These libraries provide built-in caching, revalidation on focus, error retries, deduplication, and suspense support, solving the complex edge cases of manual useEffect fetching.
Real-World Example
An infinite scroll implementation where new data is fetched as the user scrolls down (client-side only behavior).
// Client fetching is ideal for highly interactive data
// that doesn't need to be SEO-indexed, like live chat messages
// or stock tickers.Check Your Knowledge
Test your understanding of Client Fetching with these quick questions.