Skip to article content
FrontendXLesson 05 / 20

Client Boundaries and the 'use client' Directive

A version-qualified path through the Next.js App Router: server components, client boundaries, data fetching, caching layers, streaming, error handling, proxy, images, performance, testing and deployment, with the Next.js 15 and 16 behavior changes called out where they matter.

intermediate · about 50 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Place 'use client' boundaries precisely and predict what each placement ships to the browser.
  • Consume server-provided promises in client components with React's use().
  • Diagnose hydration mismatches and boundary violations from their symptoms.

Overview

#

What the directive really does

'use client' does not mark a file as client-only in isolation; it declares the entry point of a client module graph. Every module that file imports, transitively, becomes part of the client bundle, even files that look server-ish. This is why the placement rule is: mark the deepest component that needs interactivity, not the page that contains it.

snippet.tsx
// app/gallery/page.tsx (server)
import { Lightbox } from './lightbox';
export default async function Page() {
  const photos = await getPhotos();
  return <Lightbox photos={photos} />;  // only lightbox and its imports ship
}

Marking page.tsx instead would drag the data fetching module graph into the client and force the fetch to happen from the browser.

Reading promises with use()

Server components can pass unresolved promises to client components. The client unwraps them with React's use() inside a Suspense boundary:

snippet.tsx
'use client';
import { use } from 'react';
export function Stats({ data }: { data: Promise<Stats> }) {
  const stats = use(data);
  return <Chart stats={stats} />;
}

The server starts the work, ships the promise, and the boundary suspends until it resolves. This is the sanctioned bridge for request-time data into interactive islands. Unlike React hooks, use() may be called conditionally and inside loops, but it must still be called inside a component or hook and cannot be wrapped in try/catch.

Hydration and mismatch debugging

A client component renders on the server for the initial HTML and again in the browser to attach interactivity. If the two renders disagree, for example from Date.now(), Math.random(), locale-dependent formatting without a fixed locale, or browser-only checks like typeof window !== 'undefined' in render, React reports a hydration mismatch. Fix by deriving the value in an effect, seeding deterministic values on the server, or gating the divergent branch behind mounted state. Symptom to cause: mismatch warnings name the DOM difference; missing-window crashes usually mean a browser API ran during server render of a client component.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    page.tsx (server) imports ThemeToggle from './theme-toggle' which has 'use client'. theme-toggle.tsx imports ./icons which has no directive and exports SVG helper components, and ./analytics which has 'use client'. Which modules ship to the browser?

    Choose the best answer
  2. Exercise 2Explain

    A teammate says: our page is slow because we use server components, so let us add 'use client' everywhere to make it faster in the browser. Explain the two errors in this reasoning.

    Reveal the reference answer
    reference.text
    First error: server components do not make pages slow; they reduce what ships, and their cost is server compute, not browser work. Second error: 'use client' everywhere inverts the model, shipping every component's JavaScript, moving data fetching into the browser with waterfall-prone effects, and losing the ability to hold secrets server-side. The fix for perceived slowness is usually streaming with Suspense boundaries and caching, not clientification.

    Authored expected output: Both errors identified: misattributed cost and bundle-inflating remedy.

    The reasoning error is treating render location as a performance dial without measuring what ships.

  3. Exercise 3Implement

    Implement the bridge: a server page starts getStats() without awaiting, passes the promise to a client Chart wrapped in Suspense, and the Chart unwraps it with use().

    starter.tsx
    // app/dashboard/page.tsx (server)
    // TODO: start the fetch, wrap Chart in Suspense
    
    // app/dashboard/chart.tsx ('use client')
    // TODO: unwrap the promise with use()

    Reveal the reference answer
    reference.tsx
    // app/dashboard/page.tsx
    import { Suspense } from 'react';
    import { Chart } from './chart';
    import { getStats } from '@/lib/stats';
    
    export default function Dashboard() {
      const statsPromise = getStats();
      return (
        <Suspense fallback={<p>Loading chart...</p>}>
          <Chart data={statsPromise} />
        </Suspense>
      );
    }
    
    // app/dashboard/chart.tsx
    'use client';
    import { use } from 'react';
    
    export function Chart({ data }: { data: Promise<Stats> }) {
      const stats = use(data);
      return <canvas aria-label="Revenue chart" data-stats={JSON.stringify(stats)} />;
    }

    Authored expected output: The shell renders immediately; the chart streams in when the promise resolves.

    Starting the fetch before the boundary and unwrapping with use() overlaps server work with streaming.

  4. Exercise 4Debug

    This client component logs a hydration mismatch in production but not locally. Identify the likely cause and fix it. 'use client' export function Timestamp() { return <span>{new Date().toLocaleTimeString()}</span>; }

    starter.tsx
    'use client'
    export function Timestamp() {
      return <span>{new Date().toLocaleTimeString()}</span>;
    }

    Reveal the reference answer
    reference.tsx
    The server render and the browser render read the clock at different moments, so the strings differ and React reports a mismatch; the gap is larger in production where server render and hydration are further apart. Fix by rendering a deterministic server value: pass formattedTime as a prop from a server component, or compute it in a useEffect after mount and render a stable placeholder before that.

    Authored expected output: No mismatch; the displayed time comes from one authoritative source.

    Any nondeterministic render input (clock, randomness, locale) must be resolved before hydration or after it.

  5. Exercise 5Test

    Write a pure function classifyModule(source: string) that returns 'client-entry' if the first non-blank line is exactly 'use client', 'shared' otherwise. Assert on: a file starting with 'use client', a file with two leading newlines then 'use client', a file where 'use client' appears mid-file (returns shared), and a plain component file.

    starter.ts
    export function classifyModule(source: string): 'client-entry' | 'shared' {
      // TODO
    }

    Reveal the reference answer
    reference.ts
    export function classifyModule(source: string): 'client-entry' | 'shared' {
      const lines = source.split('\n');
      let i = 0;
      while (i < lines.length && lines[i].trim() === '') i++;
      return lines[i]?.trim() === "'use client'" || lines[i]?.trim() === '"use client"'
        ? 'client-entry'
        : 'shared';
    }
    
    // The directive is only meaningful as the first statement; mid-file occurrences are strings, not directives.

    Authored expected output: All four assertions pass.

    Directive position is semantic; this encodes the rule the bundler applies.

  6. Exercise 6Interview

    An interviewer asks: where have you placed client boundaries in a real app, and how did you decide? Structure an answer with one concrete example, the trade-off you weighed, and how you verified the decision.

    Reveal the reference answer
    reference.text
    Model answer shape: pick one feature, for example a data table with sortable columns inside a server-rendered page. The boundary went around the table controls only, not the page: the page fetched rows server-side and passed them down, the controls client-side held sort state and called a Server Action for server-side sorting when rows were too many to ship. The trade-off weighed was shipping row data to the browser versus paying a server round trip per sort; the decision hinged on row count and payload size. Verification: compare the client bundle chunk for the route before and after moving the boundary, and confirm the page still renders without JavaScript for the initial table. Avoid claiming measurements you did not take; describe the method instead.

    Authored expected output: One example, an explicit trade-off, and a verification method.

    Boundary placement questions test whether you optimize for what ships, not for aesthetics.

Common misconceptions

#
  • 'use client' makes a file browser-only. The file still server-renders for the initial HTML; the directive marks where the client graph begins.
  • Client components cannot receive server data. They can receive serializable props and even promises unwrapped with use().
  • Hydration mismatches are harmless warnings. They cost a full client re-render of the subtree and usually indicate a real determinism bug.
  • You should hoist 'use client' to the page for consistency. Hoisting enlarges the client bundle and moves data fetching into the browser.

Follow-up practice

#
  • nextjs-loading-streaming
  • nextjs-performance-optimization

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.