Next.jsMedium

Can Client Components fetch data directly?

Yes. Client Components can fetch data in the browser with a library such as SWR or TanStack Query, with React's use() on a promise passed from the server, or with fetch in an effect. But in the App Router the default should be fetching in Server Components, and client fetching should be reserved for data that changes after the page loads.

When client fetching makes sense

  • Polling or real-time data (notifications, live prices).
  • Infinite scroll, autocomplete and search-as-you-type.
  • Data that depends on browser-only state (geolocation, local storage).
  • Highly interactive dashboards where the client owns the cache.

Options

  • SWR / TanStack Query: caching, deduplication, revalidation on focus, retries. Recommended for most client fetching.
  • use(promise): the server starts the request and passes the promise; the client suspends until it resolves. No waterfall, no client-side cache needed.
  • useEffect + fetch: works but needs manual loading, error and race-condition handling. Avoid it for anything non-trivial.

What client code should not do

  • Call your database or use secrets. Client code is public.
  • Call your own Route Handler just to read data you could have fetched in a Server Component; that adds a network round-trip.

Where to fetch from

Client components call public APIs, Route Handlers (app/api/...) or Server Functions. Server Functions are designed for mutations; for reads, a Route Handler or server-provided promise is usually better because Server Function calls run one at a time.

Hybrid

Fetch the first page on the server, pass it as fallbackData (SWR) or initialData (TanStack Query), then let the client keep it fresh.

Code example

tsx
1// app/notifications/bell.tsx
2"use client";
3
4import useSWR from "swr";
5
6type Notification = { id: string; text: string };
7const fetcher = (url: string) => fetch(url).then((r) => r.json());
8
9export function Bell({ initial }: { initial: Notification[] }) {
10 // Seeded with server data, then refreshed every 15s in the browser
11 const { data, error, isLoading } = useSWR<Notification[]>("/api/notifications", fetcher, {
12 fallbackData: initial,
13 refreshInterval: 15_000,
14 });
15
16 if (error) return <span>!</span>;
17 return (
18 <button aria-label="Notifications">
19 🔔 {isLoading ? "…" : data?.length}
20 </button>
21 );
22}
23
24// app/layout.tsx (Server Component)
25// const initial = await getNotifications(userId);
26// <Bell initial={initial} />

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app