Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 72 · Data Fetching and Caching

Fetching Data on the Client

Learn when to fetch data in the browser in Next.js, how to stream a promise from a Server Component into use(), and when SWR or TanStack Query is worth adding.

The previous lesson showed that Server Components can fetch data and send finished HTML, with no JavaScript for the fetch. That should be your default. But some data cannot be fetched on the server ahead of time: a live counter that updates every few seconds, results that depend on what the user types, or a feed that loads more items as you scroll. For those, a Client Component has to ask for the data from the browser.

This lesson explains when client-side fetching is the right tool, how to hand a promise from a Server Component to a Client Component with React's use(), what libraries such as SWR and TanStack Query add on top of fetch, and how polling works. If you want the plain-React background first, read Data Fetching in React and Use and Suspense.

Real Next.js cannot run here, so Next.js code is read-only. The runnable examples are React 19 stand-ins with a fake API that mimic how use() and a polling hook behave in the browser.

Server first, client when needed

Fetching in the browser costs more than fetching on the server: the page must load, its JavaScript must run, and only then does the request start. The user sees a spinner where the server could have sent content. So ask first whether the data can be fetched in a Server Component.

Fetch on the server when

It is page content Articles, products, profiles.
Search engines need it Crawlers see the finished HTML.
It needs a secret Keys and queries stay private.

This is the default in the App Router.

1 / 2

A common pattern combines both: the Server Component fetches the first version of the data and passes it to a Client Component as a prop. The client shows it immediately and refreshes it later if needed. The user gets fast content and live updates.

Passing a promise to use()

React 19 has a function called use() that reads a promise during render. If the promise is still pending, the component suspends: React shows the nearest <Suspense> fallback and tries again when the promise resolves. This pairs well with Server Components, because a server page can start a request without waiting for it and let the browser's component read the result:

TSX
// app/posts/[id]/page.tsx  (real Next.js, read-only)
import { Suspense } from 'react';
import Comments from './comments';

export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const post = await getPost(id);   // awaited: the page needs this now
  const commentsPromise = getComments(id); // NOT awaited: started, passed down

  return (
    <article>
      <h1>{post.title}</h1>
      <Suspense fallback={<p>Loading comments…</p>}>
        <Comments commentsPromise={commentsPromise} />
      </Suspense>
    </article>
  );
}
TSX
// app/posts/[id]/comments.tsx  (real Next.js, read-only)
'use client';
import { use } from 'react';

export default function Comments({
  commentsPromise,
}: {
  commentsPromise: Promise<{ id: number; text: string }[]>;
}) {
  const comments = use(commentsPromise);
  return (
    <ul>
      {comments.map((comment) => (
        <li key={comment.id}>{comment.text}</li>
      ))}
    </ul>
  );
}

The post title is sent as soon as it is ready, and the comments stream in after it. Promises are one of the types that can cross the server-to-client boundary, as you saw in Inside the RSC Payload. Streaming is covered fully in Streaming with Suspense.

Do not create the promise inside a Client Component's render, for example use(fetch('/api/x')). Every render would create a new promise, suspend again and loop. Create the promise outside the component (in a Server Component, a cache or an event handler) and pass it in.

The first stand-in below shows the pattern in the browser. A fake loadComments() returns a promise, the parent keeps the current promise in state and passes it to Comments, which calls use(). Switching posts creates a new promise inside an event handler, which is allowed. Wrapping the update in startTransition keeps the old comments on screen, dimmed, while the new ones load, instead of flashing back to the fallback. Post 3 is built to fail, so you can see the error boundary take over. Click Post 3, then Post 1 to recover.

use() with a promise, Suspense and an error boundary

On first load you see the fallback, because nothing was on screen yet. After that, switching between posts 1 and 2 keeps the previous list visible while the new one loads. That difference between the first load and later updates is what transitions are for.

What a library adds

Plain fetch in an effect works, but you quickly end up rewriting the same things: caching so that going back is instant, de-duplicating the same request made by two components, retrying, refreshing when the window regains focus, polling, and keeping a list in step after a change. Two libraries cover this and both are popular in Next.js apps. They are not part of Next.js, so you install them yourself.

TSX
// SWR  (real library, read-only)
'use client';
import useSWR from 'swr';

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

export function Visitors() {
  const { data, error, isLoading } = useSWR('/api/visitors', fetcher, {
    refreshInterval: 5000, // poll every 5 seconds
  });

  if (isLoading) return <p>Loading…</p>;
  if (error) return <p>Could not load visitors</p>;
  return <p>{data.count} people online</p>;
}
TSX
// TanStack Query  (real library, read-only)
'use client';
import { useQuery } from '@tanstack/react-query';

export function Visitors() {
  const { data, error, isPending } = useQuery({
    queryKey: ['visitors'],
    queryFn: () => fetch('/api/visitors').then((response) => response.json()),
    refetchInterval: 5000,
  });

  if (isPending) return <p>Loading…</p>;
  if (error) return <p>Could not load visitors</p>;
  return <p>{data.count} people online</p>;
}

TanStack Query also needs a QueryClientProvider near the top of the tree. Since providers use state and context, they must be Client Components, a pattern described in Keeping Server Code on the Server.

SWR is smaller and simpler, and its name comes from the idea stale-while-revalidate: show cached data immediately, then fetch fresh data in the background and update. TanStack Query is larger and has more tools for mutations, pagination and infinite lists. Choose either based on how much you need. If you only have one or two small client fetches, a plain useEffect or use() may be enough.

Polling

Polling means asking again on a timer. It is the simplest way to keep a number or list fresh: no special server support, just a request every few seconds. Its cost is the extra traffic and a small delay in updates. Use it for dashboards and status indicators. If you need instant updates, look at Server-Sent Events or WebSockets instead.

Libraries make polling a single option. The second stand-in builds a tiny hook with the core ideas: a cache so a re-mounted component shows data instantly, in-flight de-duplication so two components with the same key share one request, and an interval you can turn off. Two widgets use the same key. At the start they show the same request number: the second one joined the request that the first had already started. Press Toggle second widget twice to unmount and remount it. It starts with the cached value instead of "loading…", but its timer is now offset from the first one, so each widget triggers its own request and the numbers drift apart.

A tiny polling hook with cache and de-duplication

The hook is a teaching model, not production code. It has no error handling, no retry and no cancellation of slow responses, which is exactly why real apps reach for SWR or TanStack Query once data fetching grows beyond a few places.

Whatever you choose, give users a signal while polling: a small "updated just now" label or a loading indicator that does not replace the content. Showing stale data and quietly replacing it is almost always better than flashing a spinner every few seconds.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which situation is the best fit for fetching on the client?

    Results that depend on the user's typing exist only in the browser. Page content, secrets and footers are better fetched on the server.
  2. 2. What does use(promise) do when the promise is still pending?

    use() suspends while the promise is pending and resumes rendering with its value when it resolves. A rejection is passed to the nearest error boundary.
  3. 3. Why is use(fetch('/api/x')) inside a Client Component a bug?

    The promise must be stable between renders. Create it in a Server Component, in an event handler or in a cache, then pass it in.
  4. 4. What does SWR's name, stale-while-revalidate, describe?

    The user sees something right away from the cache, and the library revalidates in the background so the data catches up.

Summary

  • Fetch on the server by default. Fetch on the client when data depends on user input, changes over time or loads on demand.
  • A Server Component can start a request, pass the promise to a Client Component and let it read it with use() inside <Suspense>.
  • Create the promise outside the Client Component's render, never inside it.
  • startTransition keeps old content on screen while new data loads, so users do not see the fallback repeatedly.
  • SWR and TanStack Query add caching, de-duplication, retries and polling, and are installed separately from Next.js.
  • Polling is a timer plus a request. It is simple, but it costs traffic and updates with a delay.

Now, see how all these pieces are stored and reused in Caching in Next.js: the Big Picture.