| | |

React Server Components 22 🧬 Bundle Discipline — Pushing “use client” to the smallest interactive leaves

⏱️ Estimated read: 17 min | |

The "use client" directive is a boundary, not a label. When a module is marked with the directive, every module it imports becomes part of the client bundle, even if those modules are never used in an interactive context. The boundary is transitive: a Client Component that imports a utility library pulls that library into the client bundle; a Client Component that imports another component pulls that component in too, regardless of whether the imported component has its own directive. The only way to keep server code out of the client bundle is to keep the boundary as far down the component tree as possible—at the interactive leaf that actually needs state, effects, or event handlers.

The React documentation states this as the primary rule for bundle discipline: Server Components should be the default, and Client Components should be “small components that are used within Server Components” . The Next.js documentation is more explicit: “To optimize the client bundle, keep Client Components as small as possible and move them to the leaves of your component tree” . The size of the client bundle is not determined by the number of "use client" directives; it is determined by the size of the subtree beneath each directive. A single directive at the root of a page pulls the entire page into the client bundle. The same directive moved to a button pulls only the button.

Key point: The "use client" boundary is transitive. A module marked with the directive and everything it imports become client code. To keep the bundle small, the directive must be placed at the interactive leaf, not at the page or layout, and the leaf must receive serializable data as props rather than importing the data-fetching modules.


Why the boundary is transitive

The import graph is the bundle graph. When the bundler encounters a module with "use client", it includes that module in the client graph. The module’s imports are then included as well, because the client code references them. This inclusion is recursive: the imported modules’ imports are included, and so on, until the entire subtree beneath the directive is in the client bundle. A Client Component that imports date-fns pulls date-fns into the client bundle. A Client Component that imports a formatter module that imports date-fns pulls both. The directive does not know which imports are used interactively; it includes all of them .

The props are the boundary for data. A Server Component can render a Client Component and pass props to it. The props are serialized and sent to the client. The Client Component receives the data without importing the module that fetched it. This is the mechanism that keeps the data-fetching code on the server. The Client Component imports only the code it needs to handle interaction—the event handler, the state hook, the animation library—and receives the data as props .

The composition pattern. A Server Component can pass Server Component children to a Client Component through the children prop. The Client Component renders the children without knowing what they contain. The children remain Server Components, and their code is not included in the client bundle. This is the pattern that allows a Client Component to wrap server-rendered content—a client-side theme provider, a client-side tooltip, a client-side modal—without pulling the content into the client graph .

The trade-off. Pushing the directive to the leaves requires more components and more prop drilling. A page that fetches data and renders a table with a sortable column header must split the table into a Server Component (the data fetch and the row rendering) and a Client Component (the sortable header). The page passes the data to the header as props, and the header calls back to the server when the sort changes. The split is more code, but the client bundle is smaller. The size of the client bundle is the trade-off for the split.


a. The root-level directive and its cost

The most common bundle discipline mistake is placing "use client" at the page or layout level. The directive is convenient because it makes every component in the file a Client Component, and the developer does not have to think about which components need interactivity. The cost is that every import in the file—and every import of those imports—enters the client bundle.

// app/dashboard/page.jsx — the root-level directive
'use client';

import { useState } from 'react';
import { Chart } from 'recharts'; // 120KB, pulled into the client bundle
import { formatDate } from 'date-fns'; // 70KB, pulled into the client bundle
import { db } from '@/lib/db'; // server-only, but imported here

export default function DashboardPage() {
  const [range, setRange] = useState('week');
  // ... rendering ...
}

The page has one piece of state—the selected range—and it imports three modules that are large or server-only. The db import is a bug: the module is server-only, and importing it in a Client Component either fails the build or pulls a server-only stub into the client bundle. The recharts and date-fns imports are not bugs; they are the cost of the root-level directive. The chart library is only needed when the chart is rendered, and the date formatter is only needed when a date is displayed, but the directive includes both in the client bundle regardless.

// app/dashboard/page.jsx — the leaf-level directive
import { db } from '@/lib/db';
import { formatDate } from 'date-fns';
import { RangeSelector } from './range-selector';
import { Chart } from './chart';

export default async function DashboardPage() {
  const data = await db.query('SELECT * FROM metrics');
  return (
    <div>
      <RangeSelector />
      <Chart data={data} />
    </div>
  );
}

// app/dashboard/range-selector.jsx — the client leaf
'use client';

import { useState } from 'react';

export function RangeSelector() {
  const [range, setRange] = useState('week');
  return (
    <select value={range} onChange={e => setRange(e.target.value)}>
      <option value="week">Week</option>
      <option value="month">Month</option>
    </select>
  );
}

The page is now a Server Component. It fetches the data and renders two children. The RangeSelector is the only Client Component, and it is small: a useState hook and a <select>. The db and date-fns imports are in the Server Component, so they never enter the client bundle. The Chart component is a Server Component that receives the data as props and renders the chart on the server. If the chart needs interactivity—tooltips, zoom—it can be split again, with a Client Component for the interactive wrapper and a Server Component for the chart data.

The date-fns import in this example is in the Server Component, which means it is used during server rendering. If a Client Component needed to format a date, it would import date-fns itself, and that import would enter the client bundle. The discipline is not “never import date-fns in a Client Component”; it is “only import it in a Client Component if the formatting happens on the client.” A date that is formatted once during server rendering does not need the formatter in the client bundle.


b. The composition pattern for wrapping server content

The composition pattern allows a Client Component to wrap Server Component children without pulling them into the client bundle. The children prop is the mechanism: the Client Component receives the server-rendered content as a prop and renders it in the client-side wrapper.

// app/theme-provider.jsx — a Client Component that wraps server content
'use client';

import { createContext, useState } from 'react';

const ThemeContext = createContext('light');

export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');
  return (
    <ThemeContext.Provider value={theme}>
      <button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
        Toggle theme
      </button>
      {children}
    </ThemeContext.Provider>
  );
}
// app/page.jsx — a Server Component that passes server children
import { ThemeProvider } from './theme-provider';
import { Chart } from './chart'; // Server Component

export default async function Page() {
  const data = await db.query('SELECT * FROM metrics');
  return (
    // The Chart is a Server Component.
    // It is passed as children to the Client Component.
    // The Chart's code is not in the client bundle.
    <ThemeProvider>
      <Chart data={data} />
    </ThemeProvider>
  );
}

The ThemeProvider is a Client Component because it uses useState and an event handler. The Chart is a Server Component because it fetches and renders data on the server. The ThemeProvider receives the Chart as children, and it renders the children without importing them. The bundler sees the Chart import in the Server Component, not in the Client Component, so the Chart remains server code. The client bundle contains the ThemeProvider and nothing else from this tree.

The composition pattern is the escape hatch from the transitivity rule. A Client Component cannot import a Server Component directly, but it can receive one as a prop. The prop is serialized as a reference to the server-rendered tree, not as the component’s code. The client renders the reference, and the server renders the component .


Complete Example Session

// ============================================
// PART 1: THE ROOT-LEVEL DIRECTIVE (WRONG)
// ============================================

// app/products/page.jsx — the whole page is a Client Component
'use client';

import { useState } from 'react';
import { Chart } from 'recharts';       // 120KB into the client bundle
import { formatCurrency } from '@/lib/format'; // 5KB
import { db } from '@/lib/db';          // server-only, build error

export default function ProductsPage() {
  const [sort, setSort] = useState('name');
  // ...
}

// The directive pulls every import into the client bundle.
// The db import is a build error.
// The chart library is in the client bundle even if
// the chart is only rendered for one route.

// ============================================
// PART 2: THE LEAF-LEVEL DIRECTIVE (CORRECT)
// ============================================

// app/products/page.jsx — the page is a Server Component
import { db } from '@/lib/db';
import { formatCurrency } from '@/lib/format';
import { SortControl } from './sort-control';

export default async function ProductsPage() {
  const products = await db.query('SELECT * FROM products');
  return (
    <div>
      <SortControl />
      <ul>
        {products.map(p => (
          <li key={p.id}>{p.name} — {formatCurrency(p.price)}</li>
        ))}
      </ul>
    </div>
  );
}

// app/products/sort-control.jsx — the client leaf
'use client';

import { useState } from 'react';

export function SortControl() {
  const [sort, setSort] = useState('name');
  return (
    <select value={sort} onChange={e => setSort(e.target.value)}>
      <option value="name">Name</option>
      <option value="price">Price</option>
    </select>
  );
}

// The db and formatCurrency imports are in the Server Component.
// Only SortControl is in the client bundle.

// ============================================
// PART 3: THE COMPOSITION PATTERN
// ============================================

// app/products/filter-wrapper.jsx — the client wrapper
'use client';

import { useState } from 'react';

export function FilterWrapper({ children }) {
  const [filter, setFilter] = useState('');
  return (
    <div>
      <input value={filter} onChange={e => setFilter(e.target.value)} />
      {/* The children are server-rendered. */}
      {/* Their code is not in the client bundle. */}
      {children}
    </div>
  );
}

// app/products/page.jsx — the server page
import { FilterWrapper } from './filter-wrapper';
import { ProductList } from './product-list'; // Server Component

export default async function Page() {
  const products = await db.query('SELECT * FROM products');
  return (
    <FilterWrapper>
      <ProductList products={products} />
    </FilterWrapper>
  );
}

// The FilterWrapper is a Client Component.
// The ProductList is a Server Component passed as children.
// The ProductList's code is not in the client bundle.

// ============================================
// PART 4: THE PROPS AS DATA BOUNDARY
// ============================================

// app/products/price-display.jsx — the client leaf
'use client';

// The client component receives the formatted string as a prop.
// It does not import the formatter.
// The formatting happens on the server.
export function PriceDisplay({ formattedPrice }) {
  return <span>{formattedPrice}</span>;
}

// app/products/page.jsx — the server page
import { formatCurrency } from '@/lib/format';
import { PriceDisplay } from './price-display';

export default async function Page() {
  const product = await db.query('SELECT * FROM products WHERE id = $1', [id]);
  return <PriceDisplay formattedPrice={formatCurrency(product.price)} />;
}

// The formatCurrency import is in the Server Component.
// The client component receives the result, not the formatter.

// ============================================
// PART 5: THE INTERACTIVE CHART SPLIT
// ============================================

// app/products/chart.jsx — the server part
import { ChartData } from './chart-data';
import { ChartInteractions } from './chart-interactions';

export async function Chart({ data }) {
  return (
    <ChartInteractions data={data}>
      <ChartData data={data} />
    </ChartInteractions>
  );
}

// app/products/chart-interactions.jsx — the client wrapper
'use client';

import { useState } from 'react';

export function ChartInteractions({ data, children }) {
  const [hovered, setHovered] = useState(null);
  return (
    <div onMouseMove={e => setHovered(e.target)}>
      {children}
      {hovered && <span>Tooltip</span>}
    </div>
  );
}

// app/products/chart-data.jsx — the server rendering
export function ChartData({ data }) {
  // The chart rendering is on the server.
  // The client wrapper receives it as children.
  return <svg>{/* chart paths */}</svg>;
}

// The chart library is imported in the Server Component.
// The client bundle contains only the interaction wrapper.

// ============================================
// PART 6: THE SERVER ACTION BOUNDARY
// ============================================

// The client leaf can call a Server Action without importing
// the action's implementation.
// app/products/sort-control.jsx
'use client';

import { useTransition } from 'react';

export function SortControl() {
  const [isPending, startTransition] = useTransition();
  return (
    <button
      onClick={() => startTransition(() => sortProducts('name'))}
      disabled={isPending}
    >
      Sort by name
    </button>
  );
}

// app/actions.js
'use server';
export async function sortProducts(field) {
  // The implementation is on the server.
  // The client holds a reference, not the code.
}

// ============================================
// PART 7: THE ANTI-PATTERN — SERVER IMPORT IN CLIENT
// ============================================

// app/products/page.jsx — a Client Component importing server code
'use client';

import { db } from '@/lib/db'; // ❌ server-only module

export function Page() {
  // This either fails the build or pulls a server stub
  // into the client bundle.
}

// The fix is to move the db import to a Server Component
// and pass the data as props.

// ============================================
// PART 8: THE ANTI-PATTERN — ROOT DIRECTIVE
// ============================================

// app/layout.jsx — a Client Component layout
'use client';

export default function Layout({ children }) {
  // The layout's imports are in the client bundle.
  // Every page that uses this layout inherits the boundary.
  return <div>{children}</div>;
}

// The fix is to keep the layout a Server Component
// and add the directive only to the interactive parts.

// ============================================
// PART 9: THE VERIFICATION — INSPECT THE CLIENT BUNDLE
// ============================================

// Build the application and inspect the client bundle.
// Search for the names of modules that should be server-only.
// If they appear, the 'use client' boundary is too high.
//
// In Next.js:
// next build
// Inspect .next/static/chunks/
//
// In a custom setup:
// Inspect the client output directory.

// ============================================
// PART 10: THE CHECKLIST
// ============================================

// [ ] The page and layout are Server Components.
// [ ] The 'use client' directive is on the interactive leaf.
// [ ] The leaf imports only the code it needs for interaction.
// [ ] The data is passed as props, not fetched in the leaf.
// [ ] The server content is passed as children, not imported.
// [ ] The server-only modules are not imported in Client Components.
// [ ] The client bundle is inspected for unexpected modules.

The ten parts covered the root-level directive, the leaf-level directive, the composition pattern, the props boundary, the chart split, the Server Action boundary, the anti-patterns, the verification, and the checklist. The through-line is that the boundary is transitive, and the size of the client bundle is the size of the subtree beneath each directive.


Quick Reference

The boundary rule

PlacementClient bundle size
Layout or pageEntire page subtree
Section wrapperThe section subtree
Interactive leafThe leaf and its imports
Server ComponentZero (code runs on server)

The composition pattern

PatternClient bundleServer bundle
Import a Server Component in a Client Component❌ Not allowedN/A
Pass a Server Component as childrenOnly the wrapperThe child
Pass data as propsOnly the consumerThe fetcher

The anti-patterns

Anti-patternConsequence
'use client' on a layout or pageEntire subtree in client bundle
Importing a server-only module in a Client ComponentBuild error or client stub
Fetching data in a Client ComponentData-fetching code in client bundle

Best Practices

✅ Do This:

// Put the directive on the interactive leaf
'use client'; export function SortControl() { /* ... */ }       // ✅

// Pass data as props to the leaf
<SortControl initialSort={sort} />                               // ✅

// Pass server content as children
<ThemeProvider><Chart data={data} /></ThemeProvider>             // ✅

// Keep the page a Server Component
export default async function Page() { /* ... */ }               // ✅

❌ Don’t Do This:

// Put the directive on the page
'use client'; export default function Page() { /* ... */ }       // ❌

// Import a server-only module in a Client Component
import { db } from '@/lib/db';                                    // ❌

// Fetch data in a Client Component
useEffect(() => { fetch('/api').then(...); }, []);                // ❌

Common Pitfalls

PitfallWhy It HappensFix
Large library in the client bundle'use client' on the pageMove the directive to the leaf
Build error on a server importServer-only module in a Client ComponentMove the import to a Server Component
Chart library in the client bundleChart rendered in a Client ComponentRender the chart on the server, pass as children
Every component is a Client ComponentThe directive is at the rootKeep the root as a Server Component

Real-World Examples

1. Leaf-level directive

'use client'; export function Toggle() { const [on, setOn] = useState(false); }

2. Data as props

<PriceDisplay formattedPrice={formatCurrency(p.price)} />

3. Server content as children

<ClientWrapper><ServerChart data={data} /></ClientWrapper>

4. Chart split

export function Chart({ data }) { return <ClientWrapper><Svg data={data} /></ClientWrapper>; }

5. Server Action reference

'use client'; import { sortProducts } from '@/app/actions';

6. Root-level anti-pattern

'use client'; export default function Page() { /* ... */ } // ❌

7. Server import anti-pattern

'use client'; import { db } from '@/lib/db'; // ❌

8. Bundle inspection

next build && ls .next/static/chunks/

9. Composition pattern

<ThemeProvider><Chart /></ThemeProvider>

10. Leaf-only interactivity

// The page fetches; the leaf toggles.

Visual

The Boundary Transitivity

┌──────────────────────────────────────────────────────────────┐
│  ROOT DIRECTIVE VS LEAF DIRECTIVE                             │
│                                                              │
│  Root directive                Leaf directive               │
│  ┌─────────────────────┐       ┌─────────────────────┐     │
│  │ 'use client'        │       │ Server Component    │     │
│  │ Page                │       │ Page                │     │
│  │ ├── Chart (client)  │       │ ├── SortControl     │     │
│  │ ├── Table (client)  │       │ │   ('use client')  │     │
│  │ ├── Formatter       │       │ ├── Table           │     │
│  │ └── db import       │       │ │   (server)        │     │
│  │                     │       │ └── Formatter       │     │
│  │ Everything client   │       │     (server)        │     │
│  └─────────────────────┘       │                     │     │
│                                 │ Only SortControl    │     │
│                                 │ in client bundle    │     │
│                                 └─────────────────────┘     │
└──────────────────────────────────────────────────────────────┘

The Composition Pattern

┌──────────────────────────────────────────────────────────────┐
│  SERVER CONTENT AS CHILDREN                                   │
│                                                              │
│  Server Component                                            │
│  ┌──────────────────────────────────────────────┐           │
│  │ <ThemeProvider>                              │           │
│  │   <Chart data={data} />  ← Server Component  │           │
│  │ </ThemeProvider>                              │           │
│  └──────────────────────┬───────────────────────┘           │
│                         │                                    │
│                         ▼                                    │
│  ┌──────────────────────────────────────────────┐           │
│  │ ThemeProvider ('use client')                 │           │
│  │                                              │           │
│  │ Receives children as a prop.                 │           │
│  │ Renders children without importing them.     │           │
│  │ The Chart's code is not in the client bundle.│           │
│  └──────────────────────────────────────────────┘           │
└──────────────────────────────────────────────────────────────┘

The Data Boundary

┌──────────────────────────────────────────────────────────────┐
│  PROPS VS IMPORTS                                             │
│                                                              │
│  ❌ Import the fetcher in the client:                          │
│  ┌─────────────────────┐                                    │
│  │ 'use client'        │                                    │
│  │ import { db } from  │  ← server code in client bundle     │
│  │   '@/lib/db'        │                                    │
│  └─────────────────────┘                                    │
│                                                              │
│  ✅ Pass the data as props:                                   │
│  ┌─────────────────────┐                                    │
│  │ 'use client'        │                                    │
│  │ function C({ data })│  ← data is serialized              │
│  │                     │  ← no db import                    │
│  └─────────────────────┘                                    │
│                                                              │
│  The Server Component fetches; the Client Component renders.│
│  The fetcher stays on the server.                           │
└──────────────────────────────────────────────────────────────┘

Summary

ItemValue
Boundary rule'use client' includes the module and all its imports
Correct placementInteractive leaf, not page or layout
Data boundaryProps, not imports
Server content boundarychildren prop, not import
Root directive costEntire subtree in client bundle
VerificationInspect the client bundle for unexpected modules

Key takeaways:

  • The directive is transitive. A Client Component includes every module it imports, recursively. The size of the client bundle is determined by the size of the subtree beneath each directive, not by the number of directives .
  • The directive belongs on the interactive leaf. A page or layout with the directive pulls the entire subtree into the client bundle. The same directive on a button pulls only the button. The page should be a Server Component that fetches data and renders children .
  • Data crosses the boundary as props, not imports. A Client Component receives serialized data from its Server Component parent. It does not import the data-fetching module. The fetcher stays on the server; the client receives the result .
  • Server content crosses the boundary as children. A Client Component can wrap Server Component content by receiving it as a prop. The child’s code is not in the client bundle. The wrapper renders the child without importing it .
  • The bundle inspection is the verification. After the build, search the client bundle for the names of modules that should be server-only. If they appear, the boundary is too high. The build output is the truth, not the source structure.

Remember: The "use client" directive is a boundary, and the boundary is transitive. The directive does not make a component interactive; it makes the component and everything it imports part of the client bundle. The discipline is to place the directive at the smallest component that actually needs interactivity, to pass data as props, and to pass server content as children. The client bundle is the result of those choices. A page with a root-level directive is a page whose entire subtree is client code. The same page with a leaf-level directive is a page whose client bundle contains one interactive component. The difference is the discipline.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!