Menu

Client-Side Data Fetching

Lesson 4: Client-Side Data Fetching

When should you fetch on the client?

Server fetching is the default, but some data belongs in the browser.

Situation Fetch on
Initial page content Server
SEO-relevant content Server
Live data that updates every few seconds (scores, notifications) Client (polling or WebSocket)
Data that depends on user interaction after load (infinite scroll, autocomplete) Client
Data from browser-only sources (geolocation, local storage) Client

Example (SWR)

'use client';
import useSWR from 'swr';

const fetcher = (url: string) => fetch(url).then((r) => r.json());

export function LiveLearners({ courseId }: { courseId: string }) {
  const { data, error, isLoading } = useSWR(
    `/api/courses/${courseId}/live`,
    fetcher,
    { refreshInterval: 10_000 }, // every 10 seconds
  );

  if (error) return <p>Could not load live count.</p>;
  if (isLoading) return <p>…</p>;
  return <p>{data.count} learners online now</p>;
}

How it works

  • The component renders on the server with a loading state, then fetches in the browser.
  • SWR caches the response, deduplicates requests, and refetches on focus and on an interval.
  • The endpoint (/api/...) is a Route Handler (Lesson 5).
Library Strength
SWR Small, simple API, made by the Next.js team
TanStack Query Powerful caching, mutations, pagination, devtools
Plain fetch in useEffect Fine for one-off cases; no caching or retries

Common mistakes

Mistake Effect Fix
Fetching all page content on the client Slow first load, weak SEO Fetch initial data on the server
useEffect fetch without cleanup Race conditions on fast changes Use SWR/TanStack Query or an abort controller
Exposing secret keys for client fetches Keys visible in the browser Call your own Route Handler, which uses the key server-side

Key takeaways

  • Fetch on the client only for live, interactive, or browser-only data.
  • Use SWR or TanStack Query rather than hand-written effects.

Try it: Add a "learners online" counter to the course page that refreshes every 10 seconds using SWR.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details