Skip to main content
FutureStack
Web & Edge Runtime
•20 min read•Last Verified: 2026-08-09

The "use client" Boundary Trap: 7 React Server Component Mistakes That Bloat Your Bundle

This technical guide details seven use client mistakes that inflate RSC bundles and demonstrates how to audit and refactor code using the Donut pattern.

Mubashir Arham

Mubashir Arham

Founder & Principal Systems Architect

The "use client" Boundary Trap: 7 React Server Component Mistakes That Bloat Your Bundle
Important

[!IMPORTANT] Direct Answer (AIEO Summary): The "use client" directive does not just mark one file—it draws a module graph boundary. Every component and npm package imported into a "use client" file gets bundled into the browser JavaScript download, even if that imported file never uses hooks or state. To keep bundles tiny, push "use client" down to the smallest interactive leaf components and pass Server Components through children slots (the Donut Pattern).

Published as Part 3 of the 10-Part FutureStack React Server Components Deep-Dive Series. Every code example, architecture diagram, and interactive React widget below is written for production React 19 & modern full-stack engineering teams.

1. What "use client" Really Tells Your Bundler

Many developers misunderstand what the "use client" directive actually does. They often think it means "this component only renders on the client." That's not quite right. The directive is much more fundamental. It's a signal to your JavaScript bundler, not a runtime check.

When your bundler sees "use client" at the top of a file, it marks that file and everything it imports as client-side code. This means all that JavaScript will be shipped to the user's browser. This distinction is critical for understanding bundle size.

The "use client" Directive: A Compiler Instruction, Not a Runtime Check

Think of "use client" as a compiler instruction, a strict boundary for your build tools. It tells tools like Webpack or Turbopack: "Stop here. Everything below this line in the import graph, including this file itself, must be bundled for the client." This isn't about when a component renders initially. Server Components can render on the server, producing HTML, even if they contain client components nested within their JSX.

The core idea behind React Server Components (RSCs) is to reduce the amount of JavaScript sent to the browser. Server Components run purely on the server, generating a special payload that describes the UI, including placeholders for client components. For a deeper dive into this payload, check out our guide on React Server Components Explained: Inside the RSC Flight Wire Protocol. Because Server Components never execute in the browser, their code—and crucially, their dependencies—never need to be part of the client-side JavaScript bundle.

The moment a file declares "use client", that promise changes. Any module that imports a client component, or any module imported by a client component, automatically becomes part of the client bundle. This is the module graph at work. It's a chain reaction.

Architecture Note

[!NOTE] The use client directive must be at the very top of the file, above all imports. If you place it anywhere else, it will be ignored by the bundler. It's a compile-time signal, not a line of code executed at runtime.

The Module Graph Boundary: Your Bundler's Blueprint

Your application isn't just a collection of files. It's a complex web of dependencies, a "module graph." Every import statement draws an arrow from one file to another. When your bundler builds your application, it walks this graph. For server components, the bundler can discard their code from the client bundle. For client components, it must include their code.

The "use client" directive acts as a hard boundary in this module graph. Imagine it as a one-way gate. Once a module passes through this gate (by being marked "use client" or by importing something that is), all its downstream dependencies are destined for the client bundle. This is true even if some of those dependencies could theoretically run on the server. The bundler has already committed them to the client.

Consider a shared utility function. If this function is imported by only server components, it stays server-side. It never makes it into the browser's JavaScript bundle. But if even one client component imports this same utility, then the utility function's code (and anything it imports) will be included in the client bundle. This happens regardless of how many server components also import it. The client component's need dictates the bundling outcome for that shared module.

This behavior is a key difference from traditional React applications. With React Server Components, you actively prune your client-side bundle by keeping as much logic as possible on the server. The Official React Server Components Reference (react.dev) clearly outlines this fundamental separation. Next.js, with its App Router, leverages this extensively, allowing developers to build full-stack React applications where server-side logic truly stays server-side. You can read more about its implementation in the Next.js App Router Server Components Documentation.

Let's look at an example that often trips up developers. Suppose you have a large data fetching library or a utility that's only needed for server-side operations, like interacting with a database or a complex API.

app/products/[id]/page.tsx
// This is a Server Component by default in Next.js App Router
import { fetchProductDetails } from '@/lib/server-data-api'; // This is a heavy, server-only utility
import { ProductDisplay } from '@/components/ProductDisplay'; // This is a client component

interface ProductPageProps {
  params: { id: string };
}

export default async function ProductPage({ params }: ProductPageProps) {
  const product = await fetchProductDetails(params.id); // Server-side data fetch

  return (
    <div>
      <h1>Product: {product.name}</h1>
      {/* ProductDisplay is a Client Component */}
      <ProductDisplay product={product} /> 
    </div>
  );
}

Now, let's look at ProductDisplay.tsx:

components/ProductDisplay.tsx
"use client"; // This marks ProductDisplay and all its imports as client-side

import { useState } from 'react';
// Imagine this import is a mistake: it pulls in the server-only utility
// because someone thought it might be useful for client-side validation later.
import { calculateDiscount } from '@/lib/server-data-api'; // 🚨 Problematic import!

interface ProductDisplayProps {
  product: {
    id: string;
    name: string;
    price: number;
    description: string;
  };
}

export function ProductDisplay({ product }: ProductDisplayProps) {
  const [quantity, setQuantity] = useState(1);

  // This function is never actually called on the client, 
  // but its code is still shipped to the browser.
  const potentialDiscount = calculateDiscount(product.price, quantity); 

  return (
    <div>
      <h2>{product.name}</h2>
      <p>{product.description}</p>
      <p>Price: ${product.price.toFixed(2)}</p>
      <input
        type="number"
        value={quantity}
        onChange={(e) => setQuantity(Number(e.target.value))}
        min="1"
      />
      <p>Total: ${(product.price * quantity).toFixed(2)}</p>
      {potentialDiscount > 0 && <p>You could save ${potentialDiscount.toFixed(2)}!</p>}
      <button onClick={() => alert('Added to cart!')}>Add to Cart</button>
    </div>
  );
}

In this scenario, fetchProductDetails and calculateDiscount might live in the same server-side library (lib/server-data-api.ts). Even though calculateDiscount is never actually called client-side, its import statement within ProductDisplay.tsx (a client component) forces the bundler to include calculateDiscount and all its own dependencies in the client bundle. This can quickly bloat your client-side JavaScript, increasing Time to First Byte (TTFB) and hydration costs. For more on TTFB, see the web.dev Time to First Byte (TTFB) Guide.

JSX Nesting vs. Import Hierarchy: The Real Bundle Size Culprit

Here's where the biggest misconception lies: many developers believe that if a client component is nested inside a server component's JSX, its impact on the bundle is somehow contained. Or, conversely, that a server component nested in a client component's JSX will magically become client-side. Neither is true.

The key distinction is between the React render tree (how components are nested in JSX) and the JavaScript module graph (how files import each other). "use client" operates on the module graph. It tells the bundler which files to include in the client bundle, based on import statements, not on how components are composed in JSX.

Consider this:

app/dashboard/page.tsx
// This is a Server Component
import { ServerSideWidget } from '@/components/ServerSideWidget';
import { ClientSideCounter } from '@/components/ClientSideCounter';

export default function DashboardPage() {
  return (
    <div>
      <h1>Dashboard</h1>
      <ServerSideWidget /> {/* This is a Server Component */}
      <ClientSideCounter /> {/* This is a Client Component */}
    </div>
  );
}

In this example, ClientSideCounter is a client component. It's rendered by DashboardPage (a server component). The fact that ClientSideCounter is nested in DashboardPage's JSX doesn't change ClientSideCounter's status. It remains a client component. Its code, and all its dependencies, will be part of the client bundle. The server component DashboardPage simply renders a placeholder for ClientSideCounter in the RSC payload, which the client then hydrates.

Crucially, ServerSideWidget (if it doesn't have "use client" and doesn't import any client components) and all its dependencies will not be part of the client bundle. This is true even though it's a sibling to ClientSideCounter in the JSX. The module graph determines the bundle, not the render tree.

The "Before" Scenario: Accidental Client Bundle Bloat

Let's revisit our ProductDisplay example, but make the calculateDiscount utility truly heavy.

lib/server-only-analytics.ts
// This file is HUGE. Imagine 500KB of complex analytics logic,
// database schema definitions, and internal API client code.
// It's designed ONLY for server-side data processing.
export function trackProductView(productId: string, userId: string) {
  // ... complex server-side analytics tracking logic ...
  console.log(`Tracking product view for ${productId} by ${userId}`);
}

export function calculateEngagementScore(data: any[]): number {
  // ... another massive function for server-side data aggregation ...
  return data.length * 100;
}

// And many more large, server-specific exports...

Now, a client component accidentally imports just one small piece from it:

components/ProductInteractions.tsx
"use client";

import { useState } from 'react';
// 🚨 Problem: This single import pulls the ENTIRE 'lib/server-only-analytics.ts'
// module (500KB+) into the client bundle!
import { trackProductView } from '@/lib/server-only-analytics'; 

interface ProductInteractionsProps {
  productId: string;
  initialLikes: number;
}

export function ProductInteractions({ productId, initialLikes }: ProductInteractionsProps) {
  const [likes, setLikes] = useState(initialLikes);

  const handleLike = () => {
    setLikes(prev => prev + 1);
    // This call will fail in the browser because trackProductView is not designed for client.
    // But its code is still there, bloating the bundle.
    // trackProductView(productId, 'current_user_id'); 
  };

  return (
    <div>
      <p>Likes: {likes}</p>
      <button onClick={handleLike}>❤️ Like</button>
      <button onClick={() => alert('Share!')}>Share</button>
    </div>
  );
}

Even if trackProductView is commented out or never called client-side, the import statement means the entire lib/server-only-analytics.ts file, and all its dependencies, are now part of your client-side JavaScript bundle. This is a common "boundary trap."

The "After" Scenario: Isolating Server-Side Dependencies

To fix this, we need to ensure server-only code is never imported by a client component. If a client component needs to trigger a server-side action, it should do so via an API route or a Server Action.

components/ProductInteractions.tsx
"use client";

import { useState } from 'react';
// Correct: No direct import of server-only utilities.
// Instead, we'll use a Server Action or API route for server-side calls.

interface ProductInteractionsProps {
  productId: string;
  initialLikes: number;
  // We can pass a server action directly as a prop,
  // or use a client-side fetch to an API route.
  onLikeAction: (productId: string) => Promise<void>; 
}

export function ProductInteractions({ productId, initialLikes, onLikeAction }: ProductInteractionsProps) {
  const [likes, setLikes] = useState(initialLikes);

  const handleLike = async () => {
    setLikes(prev => prev + 1);
    await onLikeAction(productId); // Call the server action
  };

  return (
    <div>
      <p>Likes: {likes}</p>
      <button onClick={handleLike}>❤️ Like</button>
      <button onClick={() => alert('Share!')}>Share</button>
    </div>
  );
}

And in your server component where ProductInteractions is used:

app/products/[id]/page.tsx
// This is a Server Component
import { ProductInteractions } from '@/components/ProductInteractions';
import { trackProductView } from '@/lib/server-only-analytics'; // Only imported here, on the server

// Define a Server Action that uses the server-only utility
async function handleLikeServerAction(productId: string) {
  'use server'; // Marks this function as a Server Action
  // This code runs ONLY on the server.
  trackProductView(productId, 'current_server_user_id'); 
  // ... additional server-side logic, e.g., update database ...
}

export default async function ProductPage({ params }: { params: { id: string } }) {
  // ... fetch product details ...

  return (
    <div>
      <h1>Product Details</h1>
      {/* Pass the server action to the client component */}
      <ProductInteractions productId={params.id} initialLikes={10} onLikeAction={handleLikeServerAction} />
    </div>
  );
}

Now, lib/server-only-analytics.ts is only imported by the server component (app/products/[id]/page.tsx) or the Server Action (handleLikeServerAction). It never touches a client component's import graph. This keeps its potentially massive code out of your client bundle, resulting in a significantly smaller JavaScript payload for the browser. This pattern aligns with the philosophy of frameworks like Waku Minimal React RSC Framework, which prioritize minimal client-side JavaScript.

Here's a quick comparison of the two mental models:

FeatureReact Render Tree (JSX Nesting)JavaScript Module Graph (Import Hierarchy)
What it describesThe hierarchy of components as they appear in your UI.How your JavaScript files depend on each other via import statements.
use client impactNone. It doesn't care about where components are rendered in the UI.Everything. It defines a hard boundary for client-side bundling.
Bundle size roleMinimal direct impact. A large component in JSX doesn't mean its code is bundled if it's a server component.Primary determinant. If a client component imports a module, that module (and its dependencies) is bundled for the client.
AnalogyThe blueprint of a house, showing rooms and their contents.The supply chain for all the materials needed to build the house.

Practical Implications and Mental Models

The core lesson is this: "use client" acts as a "stop sign" for your bundler. Everything that follows this sign in the import chain is destined for the browser. This means you must be extremely mindful of what your client components import.

To keep your client bundles lean:

  1. Colocate Client Logic: Keep components with "use client" and their specific dependencies in their own directories.
  2. Separate Concerns: If a utility function can be used by both server and client, consider splitting it. For example, a validation function might have a client-side version and a server-side version that imports server-only libraries.
  3. Use Server Actions or API Routes: For client components needing to interact with server-side logic (like database calls, complex computations, or analytics tracking), always route these through Server Actions or API routes. This ensures the heavy server-side code never leaks into the client bundle.
  4. Inspect Your Bundles: Tools like next build --analyze can help you visualize your bundle contents and identify large dependencies that might have accidentally slipped into your client-side JavaScript.

Understanding this module graph boundary is crucial for building performant React applications with Server Components. It directly impacts your application's Time to First Byte (TTFB) and overall user experience. By carefully managing your import statements, you can ensure that only the absolute minimum JavaScript is sent to the browser, making your applications faster and more efficient. This is a foundational principle of the Full-Stack Next.js 2026 Engineering Roadmap we advocate at FutureStack.

Interactive Engineering Lab: Try It Yourself

Experiment directly with the live interactive React asset below to see the architecture concepts from this guide update in real time—no external sandbox required.

Interactive Asset: “use client” Bundle Impact Simulator
Client JS Shipped: 286 KB
RootLayout.tsxClient (12 KB)
MarkdownParser (marked + shiki)Client (Leaked!) (194 KB)
DateFormatter (date-fns)Client (Leaked!) (62 KB)
LikeButton.tsxClient (18 KB)

Every imported child inherits the client boundary. Heavy server-only formatters bloat browser JS by 268 KB.

2. Mistake #1 & #2: Putting 'use client' on Root Layouts and Context Providers

Many developers hit a wall when they first move to React Server Components (RSCs) and Next.js App Router. They want to add a global theme or authentication provider. These providers often need client-side features like React hooks or browser APIs. The natural instinct is to mark the file containing the provider with 'use client'. This is where the bundle size trap begins.

The problem isn't just the provider itself. It's about how use client creates a boundary. Everything inside that boundary, even components that could otherwise be Server Components, gets pulled into the client-side JavaScript bundle. This can bloat your initial load by hundreds of kilobytes, sometimes even megabytes.

The Global Wrapper Trap: Why Root Layouts & Providers Get Bloated

Let's talk about the root app/layout.tsx file in Next.js. This is where you define the structure that wraps your entire application. Think of it as the outermost shell. Often, you'll want to add global features here: a ThemeProvider from a UI library, an AuthProvider for user sessions, or a QueryClientProvider for data fetching.

These providers typically use React hooks like useState or useContext. By their nature, hooks only run on the client. So, the provider component itself must be a Client Component. The mistake happens when you apply 'use client' to the app/layout.tsx file directly, or create a client component that then wraps everything in your app.

Consider a common scenario: you're building an e-commerce site. You use a UI library like Material UI or Chakra UI. You need a ThemeProvider to set global styles.

app/layout.tsx
// This is a common mistake that blows up your bundle.
'use client'; // <-- PROBLEM: This line makes the *entire app* a Client Component.

import { Inter } from 'next/font/google';
import './globals.css';
import { ThemeProvider } from '@mui/material/styles'; // Or ChakraProvider, etc.
import theme from '../theme'; // Your custom theme object
import { AuthProvider } from '../contexts/auth-context'; // Another client-side provider

const inter = Inter({ subsets: ['latin'] });

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <ThemeProvider theme={theme}> {/* Client-side component */}
          <AuthProvider> {/* Client-side component */}
            {children} {/* EVERYTHING inside children is now client-side */}
          </AuthProvider>
        </ThemeProvider>
      </body>
    </html>
  );
}

In this code, the single line 'use client' at the very top of app/layout.tsx is a silent killer for your bundle size. It means every single component rendered within the children prop, no matter how simple or static, is now treated as a Client Component. This includes your product pages, blog posts, and static marketing content.

Imagine your product page component (app/products/[slug]/page.tsx) fetches data directly from a database using a Server Component. With 'use client' on the root layout, that product page component, despite its server-side data fetching, will be bundled and sent to the browser. It will then be hydrated on the client. This defeats a core benefit of React Server Components: rendering static or data-intensive parts of your UI entirely on the server, sending only HTML, and drastically reducing client-side JavaScript.

This isn't just theoretical. I've seen projects where adding a ThemeProvider this way immediately ballooned the initial JavaScript bundle by over 200 KB (minified + gzipped). This extra size comes from the UI library's client-side runtime, its dependencies, and crucially, all the application-specific components that should have been Server Components but were accidentally pulled into the client bundle. This directly impacts your Core Web Vitals, especially Largest Contentful Paint (LCP) and Total Blocking Time (TBT).

The same problem applies to AuthProvider, QueryClientProvider, or any other context provider that needs client-side state. If you wrap your entire application's children prop with these providers, and the providers themselves are Client Components, you're effectively turning your whole app into a Client Component.

The Client Component Boundary: What Gets Pulled In

Understanding the use client directive is key here. As the React 'use client' Directive Specification explains, it marks a module and all its imported dependencies as client-side. This means the JavaScript for these modules will be sent to the browser.

When you put 'use client' at the root of your app/layout.tsx, you're saying: "This entire file, and everything it imports, and everything it renders, is for the client." This creates a large client boundary. Any Server Component rendered inside this boundary will be serialized and passed down as a prop to the Client Component, but the client-side code for rendering it will still be bundled.

This is a fundamental difference between React Server Components and traditional Server-Side Rendering (SSR). With SSR, all components render to HTML on the server. With RSCs, components can stay on the server, never sending their JavaScript to the client. This distinction is crucial for understanding why Server Components are not just "SSR done differently," but solve completely different problems, as we discuss in React Server Components vs. SSR: Why They Solve Completely Different Problems.

Warning

[!WARNING] Placing 'use client' at the root of app/layout.tsx or any top-level wrapper component is almost always a mistake. It negates many of the performance benefits of React Server Components by forcing your entire application into the client bundle. Your bundle size will suffer, leading to slower page loads and higher hydration costs.

The "Children Slot" Refactor: Shrinking Your Client Bundle

The solution is elegant and surprisingly simple: push the 'use client' boundary as deep as possible. Only the specific components that absolutely require client-side features should be marked 'use client'. Everything else should remain a Server Component by default.

This is where the "children slot" pattern comes in. The core idea is to create a separate client component that acts purely as a wrapper for your client-side providers. This component will accept children as a prop. Critically, the children prop of a Client Component is treated as a "hole" or "slot" that can be filled by Server Components. This means Server Components passed into a Client Component's children prop remain Server Components. Their JavaScript is not sent to the client.

Let's refactor the previous example.

Step 1: Create a dedicated Client Component for your providers. Make a new file, for example, app/providers.tsx (or app/components/client-providers.tsx). This file will contain all your client-side providers.

app/providers.tsx
// This file *must* be a Client Component because it uses client-side hooks/contexts.
'use client'; // <-- CORRECT: Only this specific file is marked client.

import React from 'react';
import { ThemeProvider } from '@mui/material/styles'; // Your UI library's ThemeProvider
import theme from '../theme'; // Your custom theme object
import { AuthProvider } from '../contexts/auth-context'; // Your client-side AuthProvider
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; // Example: React Query provider

// Initialize React Query client outside the component to prevent re-creation on re-renders
const queryClient = new QueryClient(); // WHY: Avoids re-creating the client, which can lose state.

export function ClientProviders({ children }: { children: React.ReactNode }) {
  return (
    <ThemeProvider theme={theme}> {/* Client-side component */}
      <AuthProvider> {/* Client-side component */}
        <QueryClientProvider client={queryClient}> {/* Client-side component */}
          {children} {/* WHY: This 'children' prop is a slot for Server Components. */}
        </QueryClientProvider>
      </AuthProvider>
    </ThemeProvider>
  );
}

In app/providers.tsx, only the ClientProviders component and its direct dependencies (like ThemeProvider, AuthProvider, QueryClientProvider) are part of the client bundle. The children prop here is a server component "hole."

Step 2: Use this ClientProviders component in your root app/layout.tsx. Your app/layout.tsx can now remain a pure Server Component.

app/layout.tsx
// This file is a Server Component by default. No 'use client' needed.
import { Inter } from 'next/font/google';
import './globals.css';
import { ClientProviders } from './providers'; // Import the new client-side wrapper

const inter = Inter({ subsets: ['latin'] });

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <ClientProviders> {/* WHY: This component is a client boundary. */}
          {children} {/* WHY: 'children' passed to ClientProviders remains a Server Component. */}
        </ClientProviders>
      </body>
    </html>
  );
}

This 10-line refactor is incredibly powerful. The app/layout.tsx file is now a Server Component. It imports ClientProviders, which is a Client Component. But because ClientProviders accepts children as a prop, the actual content of your application (all the pages and nested layouts) remains a Server Component by default.

Impact on Bundle Size: With this change, the 200+ KB of unnecessary client-side JavaScript for your main application content disappears from the initial bundle. Only the minimal code for ClientProviders and its direct client-side dependencies (the UI library's theme context, your auth context, React Query) gets sent to the browser. Your product pages, marketing pages, and other content-heavy parts of your app render entirely on the server, sending only HTML and drastically reducing the client-side JavaScript footprint.

This also improves hydration performance. Hydration is the process where React takes the server-rendered HTML and attaches client-side JavaScript event handlers. The less JavaScript the browser needs to process and hydrate, the faster your page becomes interactive. This is a key aspect of building Edge-First Systems: Building Resilient Microservices with Next.js 15 & Turbopack.

Understanding the Trade-offs and Edge Cases

The "children slot" pattern is the recommended approach for integrating client-side providers without bloating your bundle. However, it's important to understand its implications and when to apply it.

When is it okay to directly put 'use client' on a wrapper? Almost never for a root layout. For smaller, isolated subtrees that are entirely interactive and client-driven (e.g., a complex drag-and-drop component that has no server-side concerns), it might be acceptable to put 'use client' on its root. But for anything that wraps significant portions of your application, use the children slot pattern.

Data Fetching in Providers: Client-side providers often fetch data, like user authentication status. This is fine. The key is that the provider itself is client-side, but the data it fetches (or the data it receives) doesn't cause the entire app to become client-side. For instance, you might fetch initial auth status on the server and pass it as an initial prop to your AuthProvider to avoid a client-side loading flicker. Next.js App Router's caching mechanisms are powerful for this; refer to the Next.js App Router Caching Architecture Docs for more on optimizing data flow.

Nested Providers: If you have many client-side providers, simply nest them within your ClientProviders component, as shown in the example. This keeps the client boundary contained to a single file.

Mental Model: Client Component Islands Think of use client as defining an "island" in a "sea" of Server Components. You want these islands to be as small and isolated as possible. The children prop allows you to poke a hole in your client island, letting the server-side sea flow through it, keeping your application's core content server-rendered.

Here's a quick comparison of the two approaches:

FeatureBad Pattern: 'use client' on app/layout.tsxGood Pattern: ClientProviders with children slot
Client JS Bundle SizeHigh (200+ KB larger)Low (minimal client code)
Server Component UseLimited/None for contentFull (content remains Server Components)
Hydration CostHigh (more JS to process)Low (less JS to process)
Initial Load TimeSlowerFaster
Developer ExperienceSimpler initially, but performance issues laterSlightly more upfront setup, better performance
SEO ImpactPotentially worse (slower LCP)Better (faster LCP)

By adopting the "children slot" pattern, you're not just fixing a bundle size issue; you're embracing the core philosophy of React Server Components. You're ensuring that your application only sends JavaScript to the client when it's absolutely necessary for interactivity, leading to a faster, more efficient, and more resilient user experience.

Module dependency graph comparing the "use client" top-level wrapper anti-pattern against leaf-level Donut Composition
Module dependency graph comparing the "use client" top-level wrapper anti-pattern against leaf-level Donut Composition

3. Mistake #3 & #4: Barrel Files (index.ts) and Shared Utility Leaks

You've built a beautiful component library. Maybe you used an index.ts file in each folder to simplify imports. It felt organized, clean. But with React Server Components (RSC), this common pattern can silently inflate your client-side bundles. This is Mistake #3.

Then there are shared utility files. You put helper functions in lib/utils.ts because they're "just functions," right? But if these files mix server-only logic with client-only dependencies, they become Mistake #4, leaking client-side code into server components and vice-versa. Both mistakes lead to larger client bundles, slower page loads, and a worse user experience.

The Hidden Cost of Convenience: Barrel Files (index.ts)

Barrel files, typically named index.ts or index.js, re-export multiple modules from a directory. They make imports shorter: instead of import { Button } from '@/components/ui/button', you write import { Button } from '@/components/ui'. This is convenient for developers.

However, convenience often comes with a hidden cost in complex build environments like Next.js with RSC. When a server component imports anything from a barrel file, the bundler has to process that entire barrel file. If that barrel file re-exports even one client component, or a module that depends on client-side APIs, the bundler might mark the entire entry point of that barrel file as client-side. This means every module re-exported by that index.ts becomes suspect, potentially pulling in unnecessary client-side code.

Consider this common structure:

src/components/ui/index.ts
// This file is NOT marked with "use client"
export * from './button'; // button.tsx is a "use client" component
export * from './chart';   // chart.tsx is a "use client" component, depends on a large charting library
export * from './icon-picker'; // icon-picker.tsx is a "use client" component, depends on a large icon pack
export * from './tooltip'; // tooltip.tsx is a "use client" component
export * from './server-button'; // server-button.tsx is a Server Component, does NOT have "use client"

Now, imagine a server component, app/dashboard/page.tsx, needs only the ServerButton.

app/dashboard/page.tsx
// This is a Server Component by default
import { ServerButton } from '@/components/ui'; // PROBLEMATIC IMPORT

export default function DashboardPage() {
  return (
    <div>
      <h1>Dashboard Overview</h1>
      <ServerButton onClick={() => console.log('Server action fired')} />
      {/* ... other server-only components */}
    </div>
  );
}

Even though ServerButton is a Server Component, importing it from components/ui/index.ts forces the bundler to look at the entire index.ts file. Because index.ts also re-exports Button, Chart, IconPicker, and Tooltip (all client components, some with heavy dependencies), the bundler might decide that the entire components/ui module, when imported via index.ts, should be treated with client-side precautions. This can lead to the charting library and icon pack being included in your client bundle, even if app/dashboard/page.tsx never directly uses them.

This isn't always a hard error, but a silent bloat. The bundler might not explicitly mark index.ts as "use client", but its internal dependency graph analysis can still pull in client-side modules that are peers of the intended import. Tools like webpack-bundle-analyzer (accessible via next build --analyze) will show these unexpected client chunks. You'll see large, unfamiliar libraries appearing in your app-client-internals or similar client bundles.

Warning

[!WARNING] The issue with barrel files is subtle. The bundler doesn't always pull everything into the client bundle just because one item is client-side. However, the module graph becomes more complex. If the server component imports ServerButton from index.ts, and index.ts also re-exports Chart (a client component with a heavy dependency), the bundler's optimization might fail to fully tree-shake Chart's dependencies if it deems index.ts a "client-aware" entry point. The safest approach is to avoid mixing client and server component exports in a single barrel file.

Diagnosing and Fixing Barrel File Bloat

We faced this exact problem on a new dashboard feature. Our client bundle for /dashboard jumped from 75KB to over 400KB after we refactored some components into a shared ui library. The webpack-bundle-analyzer showed a massive chunk labeled chart.js and another react-icons library, neither of which were used directly on the dashboard page. The culprit? A single index.ts file in src/components/ui.

Here's how we fixed it: direct imports. Instead of importing from the barrel file, we import directly from the component's file path.

Before (Problematic Barrel File Import):

src/components/ui/index.ts
// Re-exports both client and server components
export * from './button'; // "use client"
export *2 from './chart';   // "use client", heavy
export * from './icon-picker'; // "use client", heavy
export * from './server-button'; // Server Component
app/dashboard/page.tsx
// Server Component
import { ServerButton } from '@/components/ui'; // Pulls in client-side dependencies via index.ts

export default function DashboardPage() {
  return <ServerButton label="Submit Data" />;
}

After (Direct Imports):

app/dashboard/page.tsx
// Server Component
import { ServerButton } from '@/components/ui/server-button'; // Direct import, no client-side leakage

export default function DashboardPage() {
  return <ServerButton label="Submit Data" />;
}

The difference is clear. By directly importing ServerButton from src/components/ui/server-button.tsx, the bundler only processes that specific file. It doesn't need to touch index.ts or any of its other exports. This allows RSC to effectively tree-shake unused client dependencies from your server components.

FeatureBarrel File (index.ts) Import (import { X } from '@/components/ui')Direct Import (import { X } from '@/components/ui/x')
ConvenienceHigh (shorter import paths)Lower (longer import paths)
RSC SafetyLow (high risk of client-side bloat in server components)High (isolates module dependencies)
Bundle SizePotentially much larger client bundles (Mistake #3)Optimized client bundles
Tree-shakingCan be less effective due to complex module graphHighly effective
MaintainabilityEasy to add new exports, harder to track dependenciesClear dependency tracking

The trade-off is minor developer convenience for significant performance gains. In an RSC world, explicit imports are almost always better than implicit ones facilitated by barrel files that mix client and server components.

Shared Utilities: A Silent Client-Side Intruder

Mistake #4 is similar but applies to shared utility functions. You might have a lib/utils.ts file with various helpers: data formatters, validation functions, API wrappers, etc.

lib/utils.ts
// This file is NOT marked with "use client"
import { format } from 'date-fns'; // Client-safe library
import { z } from 'zod'; // Client-safe library

export function formatDate(date: Date): string {
  return format(date, 'PPP'); // Uses date-fns
}

export function validateEmail(email: string): boolean {
  return z.string().email().safeParse(email).success; // Uses Zod
}

// This utility function uses a client-side hook,
// or imports a library that *only* works in the browser.
// Even if it's not directly called, its presence can be an issue.
export function useLocalStorage<T>(key: string, initialValue: T) {
  // This hook is inherently client-side, using browser APIs
  // ... actual implementation would be here ...
  return [initialValue, () => {}] as [T, (value: T) => void];
}

Now, a server component app/products/page.tsx needs to display formatted dates.

app/products/page.tsx
// Server Component
import { formatDate } from '@/lib/utils'; // Imports from a mixed-concern utility file
import { getProducts } from '@/lib/dal'; // Server-only data access layer

export default async function ProductsPage() {
  const products = await getProducts(); // Assume this fetches product data

  return (
    <div>
      <h1>Products</h1>
      <ul>
        {products.map(product => (
          <li key={product.id}>
            {product.name} - Added: {formatDate(product.createdAt)}
          </li>
        ))}
      </ul>
    </div>
  );
}

Here's the problem: formatDate itself is perfectly safe for server components. It uses date-fns, which is isomorphic (works on both client and server). However, the lib/utils.ts file also contains useLocalStorage, which is inherently a client-side hook.

The bundler, when it processes lib/utils.ts, might detect the client-side nature of useLocalStorage (or its dependencies). Even if app/products/page.tsx only imports formatDate, the presence of useLocalStorage in the same module can cause the bundler to include parts of lib/utils.ts (or its client-only dependencies) in the client bundle. This is because the bundler needs to ensure that if any part of lib/utils.ts could be used on the client, it's prepared for it.

This is a "leak" because server components are inadvertently pulling client-side code into their dependency graph, leading to unnecessary client bundle size. The solution is clear separation.

The server-only Guardian and Explicit Separation

To prevent shared utility leaks, we enforce strict boundaries. Code that must run on the server stays on the server. Code that must run on the client stays on the client.

The server-only package is your best friend here. It's a tiny package that contains only an "exports" field in its package.json that points to a non-existent file for client environments. If you try to import a module that imports server-only into a client component, the build will fail. This is a powerful, explicit compile-time check.

First, install it:

terminal
npm install server-only
# or
yarn add server-only
# or
pnpm add server-only

Now, let's refactor our lib/utils.ts into lib/server-utils.ts and lib/client-utils.ts.

lib/server-utils.ts
import 'server-only'; // IMPORTANT: This file can ONLY be imported by Server Components

import { format } from 'date-fns'; // Isomorphic library
import { z } from 'zod'; // Isomorphic library
import { readFileSync } from 'fs'; // Server-only API

export function formatDate(date: Date): string {
  return format(date, 'PPP');
}

export function validateEmail(email: string): boolean {
  return z.string().email().safeParse(email).success;
}

export function getServerConfig(key: string): string {
  // Example of server-only logic: reading from file system, accessing environment variables securely
  const config = JSON.parse(readFileSync('./config.json', 'utf-8'));
  return config[key];
}

// For more advanced server-side operations, like calling external APIs or database interactions,
// consider using React Server Actions as described in the official Next.js documentation
// on [Server Actions & Mutations](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations)
// or the React 'use server' guide on [react.dev](https://react.dev/reference/rsc/use-server).
lib/client-utils.ts
"use client"; // IMPORTANT: This file can ONLY be imported by Client Components

import { useState, useEffect } from 'react';

export function useLocalStorage<T>(key: string, initialValue: T) {
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      if (typeof window === 'undefined') return initialValue; // Handle SSR
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error(error);
      return initialValue;
    }
  });

  useEffect(() => {
    if (typeof window !== 'undefined') {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue] as [T, (value: T) => void];
}

// Client-side-only formatting, perhaps using a client-only library
export function formatCurrencyClient(amount: number, currency: string): string {
  if (typeof window === 'undefined') return ''; // Ensure this runs only on client
  return new Intl.NumberFormat(navigator.language, { style: 'currency', currency }).format(amount);
}

Now, our app/products/page.tsx imports formatDate from the explicitly server-only lib/server-utils.ts:

app/products/page.tsx
// Server Component
import { formatDate } from '@/lib/server-utils'; // Safe import from server-only file
import { getProducts } from '@/lib/dal';

export default async function ProductsPage() {
  const products = await getProducts();

  return (
    <div>
      <h1>Products</h1>
      <ul>
        {products.map(product => (
          <li key={product.id}>
            {product.name} - Added: {formatDate(product.createdAt)}
          </li>
        ))}
      </ul>
    </div>
  );
}

This separation guarantees that app/products/page.tsx will never inadvertently pull client-side code into its bundle because lib/server-utils.ts is explicitly marked as server-only. If a client component tried to import getServerConfig from lib/server-utils.ts, the build would fail immediately, giving you clear feedback.

This mental model extends beyond simple utilities. Database access, API key management, file system operations – all these are inherently server-only concerns. By explicitly marking such files with server-only, you create an impenetrable wall against client-side leakage. This also helps with security: you can ensure sensitive server-side logic and API keys (like those used for server actions or data fetching, which can be protected using patterns discussed in our Free JWT & Crypto Security Workbench) never accidentally end up in the browser bundle.

The server-only package acts as a powerful linter and build-time guard. It forces you to be deliberate about your module boundaries. This clarity is crucial for maintaining optimal bundle sizes and ensuring the security and performance benefits of React Server Components. When you're dealing with complex data fetching patterns, such as those that might involve eliminating request waterfalls in React Server Components, clear separation of server-only data logic is paramount. This strict separation is a cornerstone of robust, performant web applications, regardless of whether you're deploying to Vercel or Netlify.

4. Mistake #5 & #6: Passing Oversized Props & Unnecessary Client Wrappers Around Lists

You often fetch data on the server. That's a core strength of React Server Components (RSCs). The data is right there, next to your database, ready to render. But a common trap is how you then pass this data down to interactive client components. This can silently double your payload size and slow down your application.

The Double Payload Trap: Oversized Props (Mistake #5)

Imagine you have a list of products from your database. You fetch them in a Server Component. Good start. Now, you want a client-side table component to display these products, perhaps with client-side sorting or filtering. The natural instinct is to pass the entire array of product objects directly to your ProductTable client component.

app/products/page.tsx
// This is a Server Component by default
import { getProducts } from '../../lib/dal'; // Assume this fetches products from DB
import { ProductTable } from '../../components/ProductTable'; // This is a "use client" component

export default async function ProductsPage() {
  const products = await getProducts(); // Fetches all products from the database

  // MISTAKE #5: Passing the entire 'products' array to a Client Component
  // This serializes the entire product data into the React Flight payload.
  // The same data is also rendered into the initial HTML.
  // This creates a double payload.
  return (
    <main>
      <h1>Our Products</h1>
      <ProductTable products={products} /> {/* 'products' array can be huge */}
    </main>
  );
}
components/ProductTable.tsx
'use client';

import { useState } from 'react';

interface Product {
  id: string;
  name: string;
  price: number;
  description: string; // Could be a long string
  createdAt: Date;
  updatedAt: Date;
  // ... many other fields from your database schema
}

interface ProductTableProps {
  products: Product[]; // Receives the full array of products
}

export function ProductTable({ products }: ProductTableProps) {
  const [sortKey, setSortKey] = useState<keyof Product>('name');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');

  // Client-side sorting logic
  const sortedProducts = [...products].sort((a, b) => {
    // ... sorting implementation based on sortKey and sortDirection
    return 0; // Placeholder
  });

  return (
    <div>
      <table>
        <thead>
          <tr>
            <th onClick={() => setSortKey('name')}>Name</th>
            <th onClick={() => setSortKey('price')}>Price</th>
            <th>Description</th>
          </tr>
        </thead>
        <tbody>
          {sortedProducts.map((product) => (
            <tr key={product.id}>
              <td>{product.name}</td>
              <td>${product.price.toFixed(2)}</td>
              <td>{product.description.substring(0, 50)}...</td>
            </tr>
          ))}
        </tbody>
      </table>
      {/* Pagination, filters, etc. would also live here */}
    </div>
  );
}

Here's what happens:

  1. Server Render (Initial HTML): The ProductsPage Server Component fetches products. It then renders the ProductTable component. During this server render, React fully renders the ProductTable into HTML, including all the product data. This is great for SEO and initial page load speed. The browser gets the full table content immediately.
  2. React Flight Payload (Client Hydration): Because ProductTable is a "use client" component, React also needs to send its props to the client for hydration. This means the entire products array is serialized into the React Flight payload (a JSON-like format) and sent over the network to the browser.
  3. Client Hydration: Once the browser receives the JavaScript bundle and the Flight payload, React on the client-side uses this payload to "hydrate" the ProductTable component. It effectively re-renders the component with the exact same data that was already present in the initial HTML.

This is the "double payload" problem. You send the full product data once as part of the initial HTML. Then you send it again as part of the React Flight payload. If you have 1000 products, each with a large description, you've just doubled the network transfer for that data. This directly impacts your Largest Contentful Paint (LCP) score, as the browser has more data to process before the page is fully interactive. You can learn more about LCP on the web.dev Largest Contentful Paint (LCP) Guide.

Warning

[!WARNING] Be especially careful with sensitive data. Passing entire database objects to client components means they are serialized and sent to the browser. Even if not displayed, the data is technically accessible in the client's memory. React's experimental_taintObjectReference API (see react.dev) can help prevent accidental serialization of sensitive objects, but it's better to avoid passing them in the first place.

Unnecessary Client Wrappers Around Lists (Mistake #6)

Mistake #5 often leads to Mistake #6. Developers mark an entire component like ProductTable as "use client" even when most of its rendering logic could stay on the server. This is a missed opportunity for performance.

The goal should be to push the "client boundary" as deep as possible. Only the truly interactive parts need to be client components. The static display of data should remain on the server.

Let's refine our ProductTable example to avoid both mistakes. We want to keep the rendering of individual product rows on the server, while only making the sort controls interactive on the client.

Mental Model: Server Components Render "HTML Chunks", Client Components are "Interactive Widgets"

Think of your Server Component as producing large, static chunks of HTML. Within these chunks, you can embed small, interactive client widgets. These widgets only receive the minimal props they need to function.

Here's how we'd restructure our ProductTable:

  1. ProductsPage (Server Component): Fetches data. Renders the overall table structure (<table>, <thead>, <tbody>). Maps over the products to render individual ProductRow Server Components. It also renders a small SortControls client component for interaction.
  2. ProductRow (Server Component): Renders a single <tr> for a product. Purely static.
  3. SortControls (Client Component): Manages the sort state and renders sort buttons. It doesn't receive the product data itself. Instead, it might receive a callback to trigger a server action for re-sorting, or it might update URL search parameters, causing a re-render of the parent Server Component.
app/products/page.tsx
// This is a Server Component by default
import { getProducts } from '../../lib/dal';
import { ProductRow } from '../../components/ProductRow';
import { SortControls } from '../../components/SortControls';
import { Suspense } from 'react'; // For streaming, as per React Suspense Streaming Reference

// Define the type for product data (only what's needed for display)
interface ProductDisplayData {
  id: string;
  name: string;
  price: number;
  description: string;
}

// Assume getProducts now takes sort parameters
interface GetProductsOptions {
  sortKey?: string;
  sortDirection?: 'asc' | 'desc';
}

export default async function ProductsPage({
  searchParams,
}: {
  searchParams: { [key: string]: string | string[] | undefined };
}) {
  const sortKey = (searchParams.sortKey as string) || 'name';
  const sortDirection = (searchParams.sortDirection as 'asc' | 'desc') || 'asc';

  // Fetch products based on current sort parameters
  // The database query itself handles the sorting.
  const products: ProductDisplayData[] = await getProducts({ sortKey, sortDirection });

  return (
    <main>
      <h1>Our Products</h1>
      <div className="flex justify-between items-center mb-4">
        <h2>Product List</h2>
        {/* Client Component for interactive sort controls */}
        {/* It only needs the current sort state to render buttons, not the products themselves */}
        <SortControls currentSortKey={sortKey} currentSortDirection={sortDirection} />
      </div>

      <Suspense fallback={<div>Loading products...</div>}> {/* Use Suspense for streaming */}
        <table>
          <thead>
            <tr>
              <th>Name</th>
              <th>Price</th>
              <th>Description</th>
            </tr>
          </thead>
          <tbody>
            {/* Map over products to render individual Server Components */}
            {products.map((product) => (
              <ProductRow key={product.id} product={product} />
            ))}
          </tbody>
        </table>
      </Suspense>
    </main>
  );
}
components/ProductRow.tsx
// This is a Server Component by default
interface ProductDisplayData {
  id: string;
  name: string;
  price: number;
  description: string;
}

interface ProductRowProps {
  product: ProductDisplayData;
}

// ProductRow is a Server Component. It receives only the data for one row.
// It directly renders HTML. No client-side JavaScript bundle for this.
export function ProductRow({ product }: ProductRowProps) {
  return (
    <tr key={product.id}>
      <td>{product.name}</td>
      <td>${product.price.toFixed(2)}</td>
      <td>{product.description.substring(0, 0)}...</td> {/* Truncate description on server */}
    </tr>
  );
}
components/SortControls.tsx
'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import { useCallback } from 'react';

interface SortControlsProps {
  currentSortKey: string;
  currentSortDirection: 'asc' | 'desc';
}

export function SortControls({ currentSortKey, currentSortDirection }: SortControlsProps) {
  const router = useRouter();
  const searchParams = useSearchParams();

  // Create a new URLSearchParams object with the updated sort parameters
  const createQueryString = useCallback(
    (name: string, value: string) => {
      const params = new URLSearchParams(searchParams.toString());
      params.set(name, value);
      return params.toString();
    },
    [searchParams]
  );

  const handleSortChange = (key: string) => {
    let newDirection: 'asc' | 'desc' = 'asc';
    if (currentSortKey === key) {
      // Toggle direction if same key is clicked
      newDirection = currentSortDirection === 'asc' ? 'desc' : 'asc';
    }

    // Update URL search parameters, which triggers a new server fetch
    router.push(`?${createQueryString('sortKey', key)}&${createQueryString('sortDirection', newDirection)}`);
  };

  return (
    <div className="flex gap-2">
      <button
        onClick={() => handleSortChange('name')}
        className={`px-3 py-1 rounded ${currentSortKey === 'name' ? 'bg-blue-500 text-white' : 'bg-gray-200'}`}
      >
        Name {currentSortKey === 'name' && (currentSortDirection === 'asc' ? '↑' : '↓')}
      </button>
      <button
        onClick={() => handleSortChange('price')}
        className={`px-3 py-1 rounded ${currentSortKey === 'price' ? 'bg-blue-500 text-white' : 'bg-gray-200'}`}
      >
        Price {currentSortKey === 'price' && (currentSortDirection === 'asc' ? '↑' : '↓')}
      </button>
      {/* Add more sort options */}
    </div>
  );
}

In this revised structure:

  • The ProductsPage Server Component fetches the data already sorted from the database. This is efficient; your database is optimized for this. For complex data operations, always leverage your data layer, whether it's PostgreSQL vs. Supabase Architecture Benchmark or another solution.
  • The ProductRow component remains a Server Component. It receives only the data for a single product and renders its <tr> element. This means no client-side JavaScript bundle for individual rows.
  • The SortControls is a client component. It only receives the current sort state as props. When a user clicks a sort button, it updates the URL's search parameters (router.push). This triggers a full page refresh in Next.js, causing the ProductsPage Server Component to re-run, re-fetch the data with the new sort order, and render a fresh HTML table.
  • The initial HTML payload contains the full, sorted table. The React Flight payload for hydration only contains the minimal JavaScript for the SortControls component, drastically reducing the client-side bundle size.
  • Suspense is used to stream the product list, improving perceived loading performance. Refer to the React Suspense Streaming Reference (react.dev) for more details.

Performance Comparison: Before vs. After

Let's look at the impact of these two approaches:

| Feature | "use client" Wrapper (Bad) | Server Component + Client Slots (Good) | | Initial HTML Payload | Full data rendered. | Full data rendered (ideal for speed and SEO).

5. Mistake #7: Reaching for useEffect Fetching Instead of Server Composition

Many developers coming from traditional Single-Page Application (SPA) architectures instinctively reach for useEffect to fetch data. This habit, deeply ingrained from years of client-side rendering, creates significant performance bottlenecks in React Server Component (RSC) applications. When you mark a component with 'use client', you opt into the client bundle. If that client component then fetches its own data using useEffect, you've introduced a client-side data waterfall.

Imagine a user clicking a tab in your UI. If the content for that tab then triggers a useEffect to fetch data, the browser first downloads the client component, then renders a loading state, then makes a network request back to your API, then waits for the response, and finally renders the data. This sequence of events adds unnecessary latency and bloats the client bundle with data fetching logic. It directly contradicts the core benefit of Server Components: pre-fetching and rendering data on the server before it ever reaches the browser.

The Client-Side Waterfall Trap: useEffect and Old Habits

Consider a common scenario: a product detail page with multiple tabs—"Description," "Specifications," "Reviews." If each tab's content is a client component that fetches its own data when selected, you're setting up a client-side waterfall. The initial page load might be fast because the main product data is server-rendered. However, clicking the "Reviews" tab, for instance, triggers a new client-side fetch.

This means:

  1. Increased Latency: The user experiences a delay between clicking the tab and seeing the content. This is a direct consequence of the extra network round trip from browser to API.
  2. Larger Client Bundles: The client component needs to include all the data fetching libraries (e.g., fetch, axios) and the logic to manage loading, error, and success states. This adds bytes to your JavaScript bundle, slowing down initial page load and hydration.
  3. Wasted Server Resources: Your server is perfectly capable of fetching this data once, bundling it with the component, and sending it down. Instead, you're offloading that work to potentially many client browsers, only for them to ask the server for the same data again.

In a traditional SPA, this pattern was unavoidable. With React Server Components, it's a missed opportunity for significant performance gains. We want to deliver fully-formed UI segments with their data already present, minimizing client-side computation and network requests.

Server Composition: Passing Pre-Fetched Data via Slots

The most effective way to avoid client-side data waterfalls is through server composition. Instead of a client component fetching data, a parent Server Component fetches all the necessary data upfront. It then renders specific child Server Components, or even entire UI sections, and passes them down as props to any interactive client components. Think of these as "slots" that your client component fills with server-rendered content.

This approach leverages the core strength of Server Components: they run on the server, have direct database access, and can fetch data without an additional network hop from the client. The data is fetched, the component is rendered, and only the resulting HTML (or RSC payload) is sent to the client.

Let's illustrate with our tabbed product detail example.

Before (Bad: Client-side useEffect fetch):

app/products/[id]/ProductReviewsTab.tsx
'use client';

import { useEffect, useState } from 'react';
import type { Review } from '@/lib/types'; // Assuming types are defined

interface ProductReviewsTabProps {
  productId: string;
}

export default function ProductReviewsTab({ productId }: ProductReviewsTabProps) {
  const [reviews, setReviews] = useState<Review[] | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    // This fetch happens on the client, after the component mounts.
    // It creates a client-side waterfall.
    const fetchReviews = async () => {
      setIsLoading(true);
      setError(null);
      try {
        const response = await fetch(`/api/products/${productId}/reviews`);
        if (!response.ok) {
          throw new Error('Failed to fetch reviews');
        }
        const data: Review[] = await response.json();
        setReviews(data);
      } catch (err) {
        setError((err as Error).message);
      } finally {
        setIsLoading(false);
      }
    };

    fetchReviews();
  }, [productId]); // Re-runs if productId changes

  if (isLoading) return <p>Loading reviews...</p>;
  if (error) return <p className="text-red-500">Error: {error}</p>;
  if (!reviews || reviews.length === 0) return <p>No reviews yet.</p>;

  return (
    <div className="space-y-4">
      {reviews.map((review) => (
        <div key={review.id} className="border p-4 rounded-lg">
          <p className="font-semibold">{review.author}</p>
          <p className="text-sm text-gray-600">{review.rating} stars</p>
          <p className="mt-2">{review.comment}</p>
        </div>
      ))}
    </div>
  );
}

Now, let's refactor this using server composition. The ProductReviewsTab becomes a Server Component, and the interactive tab switcher (ProductTabs) remains a client component.

After (Good: Server Composition with Slots):

First, the Server Component that fetches and renders reviews:

app/products/[id]/ProductReviews.tsx
// This is a Server Component, it fetches data directly on the server.
import { getProductReviews } from '@/lib/dal'; // Data Access Layer
import type { Review } from '@/lib/types';

interface ProductReviewsProps {
  productId: string;
}

// This component is purely for displaying reviews, no client-side interactivity needed.
export default async function ProductReviews({ productId }: ProductReviewsProps) {
  // Data fetching happens on the server before anything is sent to the client.
  const reviews: Review[] = await getProductReviews(productId);

  if (!reviews || reviews.length === 0) {
    return <p className="p-4">No reviews yet for this product.</p>;
  }

  return (
    <div className="space-y-4 p-4">
      <h3 className="text-xl font-bold">Customer Reviews ({reviews.length})</h3>
      {reviews.map((review) => (
        <div key={review.id} className="border p-4 rounded-lg shadow-sm">
          <p className="font-semibold text-lg">{review.author}</p>
          <p className="text-sm text-gray-600">Rating: {review.rating} / 5</p>
          <p className="mt-2 text-gray-800">{review.comment}</p>
          {review.date && <p className="text-xs text-gray-400 mt-1">Reviewed on {new Date(review.date).toLocaleDateString()}</p>}
        </div>
      ))}
    </div>
  );
}

Next, the client component that manages the tabs but receives the fully rendered content as a prop:

app/products/[id]/ProductTabs.tsx
'use client';

import { useState, type ReactNode } from 'react';

interface ProductTabsProps {
  descriptionSlot: ReactNode; // Receives a server-rendered component
  specificationsSlot: ReactNode; // Receives a server-rendered component
  reviewsSlot: ReactNode; // Receives a server-rendered component
}

export default function ProductTabs({ descriptionSlot, specificationsSlot, reviewsSlot }: ProductTabsProps) {
  const [activeTab, setActiveTab] = useState<'description' | 'specs' | 'reviews'>('description');

  return (
    <div className="w-full">
      <div className="border-b border-gray-200">
        <nav className="-mb-px flex space-x-8" aria-label="Tabs">
          <button
            onClick={() => setActiveTab('description')}
            className={`whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm focus:outline-none ${
              activeTab === 'description'
                ? 'border-indigo-500 text-indigo-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            Description
          </button>
          <button
            onClick={() => setActiveTab('specifications')}
            className={`whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm focus:outline-none ${
              activeTab === 'specifications'
                ? 'border-indigo-500 text-indigo-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            Specifications
          </button>
          <button
            onClick={() => setActiveTab('reviews')}
            className={`whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm focus:outline-none ${
              activeTab === 'reviews'
                ? 'border-indigo-500 text-indigo-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            Reviews
          </button>
        </nav>
      </div>

      <div className="mt-4">
        {activeTab === 'description' && descriptionSlot}
        {activeTab === 'specifications' && specificationsSlot}
        {activeTab === 'reviews' && reviewsSlot}
      </div>
    </div>
  );
}

Finally, the parent Server Page that orchestrates everything:

app/products/[id]/page.tsx
import ProductTabs from './ProductTabs';
import ProductDescription from './ProductDescription'; // Assume this is also a Server Component
import ProductSpecifications from './ProductSpecifications'; // Assume this is also a Server Component
import ProductReviews from './ProductReviews'; // Our new Server Component

interface ProductPageProps {
  params: { id: string };
}

export default async function ProductPage({ params }: ProductPageProps) {
  const productId = params.id;

  // All data fetching for all tabs happens here, on the server, in parallel or sequence.
  // The client never initiates a data fetch for these sections.
  // This is the core of server composition.
  return (
    <div className="container mx-auto p-4">
      <h1 className="text-3xl font-bold mb-6">Product Details Page</h1>
      <ProductTabs
        descriptionSlot={<ProductDescription productId={productId} />}
        specificationsSlot={<ProductSpecifications productId={productId} />}
        reviewsSlot={<ProductReviews productId={productId} />} // Pass the server-rendered component
      />
    </div>
  );
}

In this improved setup, ProductPage (a Server Component) fetches all the data for all tabs. It then renders ProductDescription, ProductSpecifications, and ProductReviews (all Server Components) and passes their fully rendered output as ReactNode props to the ProductTabs client component. When the user clicks a tab, ProductTabs simply toggles which pre-rendered content is visible. No new network requests are made from the client. This significantly reduces client-side JavaScript, improves perceived performance, and eliminates client-side waterfalls. You can learn more about how this data travels in the React Server Components Explained: Inside the RSC Flight Wire Protocol article.

Engineering Tip

[!TIP] Always prefer passing fully-rendered Server Components as children or other ReactNode props to client components. This ensures all data fetching and initial rendering happens on the server, minimizing client-side JavaScript and eliminating client-side data waterfalls.

React 19 use() and Promises: When Client-Side Async is Unavoidable

While server composition is the preferred method, there are rare cases where a client component must interact with asynchronous data that isn't fully pre-rendered. Perhaps it's a highly dynamic form that fetches options based on user input, or a component that needs to resolve a Promise that was intentionally passed down from the server. React 19 introduces the use() hook, which allows you to read the value of a Promise directly within a component (client or server).

The key distinction here is where the Promise originates. With use(), you are still aiming for the Promise to be created and initiated on the server. The server component starts the asynchronous operation, gets a Promise, and then passes that Promise down to a client component. The client component then uses use() to "unwrap" that Promise. This still avoids the client initiating the fetch itself.

When to consider use() with Promises from the server:

  • You have an interactive client component that needs to render a loading state based on an async operation that's already underway on the server.
  • The data is highly dynamic, but the initial request for that dynamic data can still be kicked off by the server.
  • You are building a client component that needs to render different UI based on the resolved value of a server-initiated Promise.

Let's adapt our example. Instead of passing a fully rendered ProductReviews component, we pass the Promise of reviews to the ProductTabs component.

lib/dal.ts
// This is a simplified DAL function, simulating an async database call.
import type { Review } from './types';

export async function getProductReviewsPromise(productId: string): Promise<Review[]> {
  console.log(`Fetching reviews for product ${productId} on the server...`);
  // Simulate network latency and database query
  await new Promise(resolve => setTimeout(resolve, Math.random() * 1000 + 500));
  const reviews = [
    { id: '1', author: 'Alice', rating: 5, comment: 'Great product!' },
    { id: '2', author: 'Bob', rating: 4, comment: 'Good value for money.' },
  ];
  return reviews.filter(review => review.id.startsWith(productId[0])); // Simple filter for demo
}

Now, the client component will use() this Promise:

app/products/[id]/ProductReviewsClient.tsx
'use client';

import { use } from 'react'; // React 19's use hook
import type { Review } from '@/lib/types';

interface ProductReviewsClientProps {
  reviewsPromise: Promise<Review[]>; // Receives a Promise from the server
}

export default function ProductReviewsClient({ reviewsPromise }: ProductReviewsClientProps) {
  // The use() hook unwraps the Promise. This component suspends until the Promise resolves.
  // This is a client component, but the Promise was initiated on the server.
  const reviews = use(reviewsPromise);

  if (!reviews || reviews.length === 0) {
    return <p className="p-4">No reviews yet for this product.</p>;
  }

  return (
    <div className="space-y-4 p-4">
      <h3 className="text-xl font-bold">Customer Reviews ({reviews.length})</h3>
      {reviews.map((review) => (
        <div key={review.id} className="border p-4 rounded-lg shadow-sm">
          <p className="font-semibold text-lg">{review.author}</p>
          <p className="text-sm text-gray-600">Rating: {review.rating} / 5</p>
          <p className="mt-2 text-gray-800">{review.comment}</p>
        </div>
      ))}
    </div>
  );
}

And the parent Server Page would pass this Promise:

app/products/[id]/page.tsx
import ProductTabs from './ProductTabs';
import ProductDescription from './ProductDescription';
import ProductSpecifications from './ProductSpecifications';
import ProductReviewsClient from './ProductReviewsClient'; // Our client component that uses the Promise
import { getProductReviewsPromise } from '@/lib/dal'; // Function that returns a Promise

interface ProductPageProps {
  params: { id: string };
}

export default async function ProductPage({ params }: ProductPageProps) {
  const productId = params.id;

  // The Promise is initiated here, on the server.
  const reviewsPromise = getProductReviewsPromise(productId);

  return (
    <div className="container mx-auto p-4">
      <h1 className="text-3xl font-bold mb-6">Product Details Page</h1>
      <ProductTabs
        descriptionSlot={<ProductDescription productId={productId} />}
        specificationsSlot={<ProductSpecifications productId={productId} />}
        // Pass the Promise directly to the client component
        reviewsSlot={<ProductReviewsClient reviewsPromise={reviewsPromise} />}
      />
    </div>
  );
}

This pattern is a good bridge for cases where you need client-side interactivity around data that's still fundamentally server-sourced. It avoids the client component making its own fetch call, but allows the client component to manage the loading state and rendering based on the Promise's resolution.

Here's a comparison of the three approaches:

FeatureuseEffect (Client-side Fetch)Server Composition (Slots)use() with Server-Initiated Promise
Data OriginClient initiates HTTP request to APIServer fetches data directly from DB/APIServer fetches data (returns Promise), client resolves
Network HopsClient -> API (extra round trip)Server -> DB (no client-side data fetch)Server -> DB (no client-side data fetch)
Loading StateManaged by client useState, often visible flickerNo client loading state for initial content, already renderedClient suspends until Promise resolves (built-in)
Bundle SizeClient bundle includes fetching logic & librariesClient bundle is minimal, only UI logicClient bundle is minimal, only UI logic and use() call
PerformancePoor, client-side waterfalls, higher TTIExcellent, data pre-fetched and rendered on serverGood, data fetch initiated early on server
ComplexityFamiliar for SPA developers, but problematic for RSCRequires mental shift, clear component boundariesModern React feature, requires React 19 or compatible
Use CaseAvoid for most data fetching in RSC appsDefault for static/dynamic content in interactive UIsDynamic data needed by client, but pre-fetched by server

Practical Considerations and Trade-offs

While useEffect for data fetching is a common anti-pattern in RSC architectures, it's important to understand the nuances.

When to Absolutely Avoid useEffect for Data:

  • Initial Page Load Data: Any data needed for the initial render of a page or a significant part of it should be fetched on the server.
  • Data for Tabs/Modals/Drawers: As demonstrated, content for interactive UI elements should be pre-fetched and passed as slots.
  • Data that powers critical UI: If the UI is broken without the data, fetch it on the server.

When use() with Server-Initiated Promises is a Good Fit:

  • Progressive Enhancement: You might have a complex client-side chart component that needs data. The server can fetch the data, pass the Promise, and the chart component can then use() it, perhaps showing a skeleton while it resolves.
  • User-Specific, Early Data: For example, a user's notification count. The server can fetch this early, pass the Promise to a client-side header component, which then use()s it.

Security Implications: Keeping data fetching on the server side has significant security benefits. When you fetch data in a Server Component, your database credentials and API keys never leave the server. If you use useEffect on the client to fetch data, you often need to expose an API endpoint that might require authentication or authorization. While proper API security measures are essential (see OWASP Top 10 Web Application Security Risks), minimizing client-side data fetching reduces the attack surface. For mutations and form submissions, always prefer React 'use server' Server Functions or Next.js Server Actions combined with hooks like React useActionState. These patterns ensure your data mutations are handled securely on the server.

The mental shift from an SPA mindset to a Server Component mindset is crucial. You're no longer thinking of the client as the primary data orchestrator. Instead, the server is the powerful orchestrator, preparing and delivering rich, data-filled UI chunks. Embracing this shift is fundamental for building high-performance, maintainable applications in the future of React, as outlined in our Full-Stack Next.js 2026 Engineering Roadmap. The closer your data fetching is to your data source, the faster and more efficient your application will be, especially when considering Edge Computing Architecture principles.

6. Mastering the Donut Composition Pattern (With 4 Production Examples)

The "use client" directive is powerful, but it's also a boundary trap. Once you mark a component as use client, everything rendered inside it – its own JSX and any components it directly imports and renders – becomes part of the client bundle. This is true even if that content could have been server-rendered. This is where many applications accidentally bloat their JavaScript bundles.

The Donut Composition pattern solves this. It lets you build interactive client components that contain heavy, server-rendered content. Think of it like a donut: the client component is the interactive, lightweight "hole" (the glazed part you hold), and the server component is the rich, static "donut" (the cake itself). The client component provides the interactivity, but the bulk of the content and data fetching stays on the server.

The Core Idea: Client Shells, Server Donuts

Many UI patterns need client-side interactivity: tabs, accordions, modals, sticky elements. If these interactive components also render complex, data-intensive content, you're faced with a choice. You can make the entire component use client, pulling all that heavy content into the client bundle. Or, you can use Donut Composition.

The trick lies in the children prop. When a Server Component renders a use client component and passes other Server Components (or plain JSX) as its children, those children remain Server Components. They are rendered on the server and then hydrated into the client component's slot. This means the client component's bundle size only includes its own interactive logic, not the heavy content it displays.

Consider a simple ClientButton component that needs a click handler. If this button's children prop is a complex, data-driven ServerProductTitle component, the ClientButton bundle won't include ServerProductTitle's code. ServerProductTitle renders on the server, and its resulting HTML is streamed to the browser. The ClientButton then hydrates around this pre-rendered HTML. This mechanism is fundamentally different from traditional SSR, where the entire page is rendered on the server, but then re-rendered on the client. With React Server Components, the server-rendered parts never re-render on the client, keeping your client bundle minimal. For a deeper dive into these distinctions, read about React Server Components vs. SSR: Why They Solve Completely Different Problems.

Here's a mental model:

AspectTraditional use client (Bloated)Donut Composition (Optimized)
Interactive Shelluse client component, renders its own UI and all content.use client component, renders its own UI, accepts children.
Heavy ContentRendered inside the use client component, bundled with it.Rendered on the server as children, passed into the use client shell.
Bundle SizeLarger, includes interactive logic + all content logic/dependencies.Smaller, only interactive logic. Content logic stays on server.
Data FetchingClient component either fetches on client, or receives all data props.Server-rendered children fetch their own data on the server. Client component can fetch its own minimal data.
Initial Load TimeSlower due to larger JS bundle download and parse.Faster, minimal JS for interactivity, heavy content streamed as HTML.
SecurityServer-side data might accidentally leak to client-side bundle.Sensitive data remains on the server, only HTML output reaches client.

Pattern in Action: Interactive Tabs and Accordions

Let's look at how this works in practice with common UI components.

Example 1: Interactive Tabs with Server-Rendered Content

Imagine a product page with tabs for "Description", "Specifications", and "Reviews". Each tab's content is complex, pulling data from a database. If your Tabs component is use client, and it directly renders DescriptionPanel, SpecificationsPanel, and ReviewsPanel, then all that content's logic and dependencies get bundled.

With Donut Composition, the ClientTabs component only manages the active tab state and renders the tab headers. The actual content for each tab is a Server Component, passed in as children.

components/ClientTabs.tsx
// components/ClientTabs.tsx
'use client'; // This component needs client-side state for active tab

import React, { useState, type ReactNode } from 'react';

// Define the shape of a tab item
interface TabItemProps {
  label: string;
  id: string;
  children: ReactNode; // The content for this tab, rendered on the server
}

// ClientTabs component: handles active tab state and renders tab headers
export function ClientTabs({ children }: { children: ReactNode[] }) {
  // We expect children to be an array of our ServerTabContent components
  const tabs = React.Children.toArray(children) as React.ReactElement<TabItemProps>[];

  // Initialize active tab to the first tab's ID
  const [activeTabId, setActiveTabId] = useState(tabs[0]?.props.id);

  return (
    <div className="w-full">
      {/* Tab Headers */}
      <div className="flex border-b border-gray-200 mb-4">
        {tabs.map((tab) => (
          <button
            key={tab.props.id}
            onClick={() => setActiveTabId(tab.props.id)}
            className={`py-2 px-4 text-sm font-medium focus:outline-none 
                        ${activeTabId === tab.props.id 
                          ? 'border-b-2 border-blue-600 text-blue-600' 
                          : 'text-gray-500 hover:text-gray-700'}`}
          >
            {tab.props.label}
          </button>
        ))}
      </div>

      {/* Tab Content - only render the active tab's children */}
      <div>
        {tabs.map((tab) => (
          <div 
            key={tab.props.id} 
            className={activeTabId === tab.props.id ? 'block' : 'hidden'}
          >
            {/* This 'children' prop is the server-rendered content */}
            {tab.props.children} 
          </div>
        ))}
      </div>
    </div>
  );
}

// This is a dummy component used to define the structure for tab items.
// Its 'children' prop will contain the actual server-rendered content.
// It doesn't need 'use client' because it's just a structural wrapper.
export function ServerTabContent({ label, id, children }: TabItemProps) {
  return <>{children}</>; // Simply renders its children
}

Now, let's see how page.tsx uses these. ServerTabContent is implicitly a Server Component because it doesn't have 'use client'. Its children (the actual product details, reviews, etc.) are also Server Components.

app/product/[slug]/page.tsx
// app/product/[slug]/page.tsx
import { ClientTabs, ServerTabContent } from '@/components/ClientTabs';
import { Suspense } from 'react';

// Mock data fetching functions (these would be actual DB calls in production)
async function getProductDescription(slug: string) {
  // Simulate a database call or API fetch
  await new Promise(resolve => setTimeout(resolve, 500)); 
  return `This is the detailed description for product "${slug}". It's a fantastic item with many features. This content is rendered on the server.`;
}

async function getProductSpecifications(slug: string) {
  await new Promise(resolve => setTimeout(resolve, 800));
  return `Specifications for "${slug}": Weight: 1.2kg, Dimensions: 10x20x5 cm, Material: Aluminum. More server-rendered details here.`;
}

async function getProductReviews(slug: string) {
  await new Promise(resolve => setTimeout(resolve, 1200));
  return `Reviews for "${slug}": "Excellent product!" (5 stars), "Highly recommend." (4.5 stars). There are 1,234 reviews in total. This comes from the server.`;
}

// Server Component for Description
async function DescriptionPanel({ slug }: { slug: string }) {
  const description = await getProductDescription(slug);
  return (
    <div className="p-4 bg-gray-50 rounded-lg">
      <h3 className="text-lg font-semibold mb-2">Product Description</h3>
      <p>{description}</p>
      <p className="mt-2 text-sm text-gray-600">This description was fetched and rendered on the server.</p>
    </div>
  );
}

// Server Component for Specifications
async function SpecificationsPanel({ slug }: { slug: string }) {
  const specs = await getProductSpecifications(slug);
  return (
    <div className="p-4 bg-gray-50 rounded-lg">
      <h3 className="text-lg font-semibold mb-2">Technical Specifications</h3>
      <p>{specs}</p>
      <p className="mt-2 text-sm text-gray-600">These specs were fetched and rendered on the server.</p>
    </div>
  );
}

// Server Component for Reviews
async function ReviewsPanel({ slug }: { slug: string }) {
  const reviews = await getProductReviews(slug);
  return (
    <div className="p-4 bg-gray-50 rounded-lg">
      <h3 className="text-lg font-semibold mb-2">Customer Reviews</h3>
      <p>{reviews}</p>
      <p className="mt-2 text-sm text-gray-600">These reviews were fetched and rendered on the server.</p>
    </div>
  );
}

export default async function ProductPage({ params }: { params: { slug: string } }) {
  const { slug } = params;

  return (
    <main className="container mx-auto p-6">
      <h1 className="text-3xl font-bold mb-6">Product Details: {slug.toUpperCase()}</h1>
      
      <ClientTabs>
        {/* Each ServerTabContent is implicitly a Server Component.
            Its children (DescriptionPanel, SpecificationsPanel, ReviewsPanel)
            are also Server Components and are rendered entirely on the server. */}
        <ServerTabContent label="Description" id="description">
          {/* Suspense allows streaming of individual tab content */}
          <Suspense fallback={<div>Loading description...</div>}>
            <DescriptionPanel slug={slug} />
          </Suspense>
        </ServerTabContent>

        <ServerTabContent label="Specifications" id="specifications">
          <Suspense fallback={<div>Loading specifications...</div>}>
            <SpecificationsPanel slug={slug} />
          </Suspense>
        </ServerTabContent>

        <ServerTabContent label="Reviews" id="reviews">
          <Suspense fallback={<div>Loading reviews...</div>}>
            <ReviewsPanel slug={slug} />
          </Suspense>
        </ServerTabContent>
      </ClientTabs>
    </main>
  );
}

In this setup, ClientTabs.tsx is minimal. It only contains the logic for managing activeTabId and rendering simple buttons. The heavy lifting of fetching product data and rendering rich panels happens entirely on the server within DescriptionPanel, SpecificationsPanel, and ReviewsPanel. These server components are passed as children to ServerTabContent, which then passes them to ClientTabs. The Suspense boundaries around each panel ensure that the tab headers and the initial active tab content can stream immediately, while other tab content loads in the background, significantly improving Largest Contentful Paint (LCP). You can learn more about this streaming behavior in the React Suspense Streaming Reference (react.dev).

Example 2: Collapsible Accordions

The same principle applies to accordions. The ClientAccordion component provides the interactive open/close toggle, while the AccordionItem's content remains server-rendered.

components/ClientAccordion.tsx
// components/ClientAccordion.tsx
'use client';

import React, { useState, type ReactNode } from 'react';

interface AccordionItemProps {
  title: string;
  id: string;
  children: ReactNode;
}

export function ClientAccordion({ children }: { children: ReactNode[] }) {
  const items = React.Children.toArray(children) as React.ReactElement<AccordionItemProps>[];
  const [openItemId, setOpenItemId] = useState<string | null>(null); // State to manage which item is open

  const toggleItem = (id: string) => {
    setOpenItemId(prevId => (prevId === id ? null : id));
  };

  return (
    <div className="border border-gray-200 rounded-lg">
      {items.map((item) => (
        <div key={item.props.id} className="border-b border-gray-200 last:border-b-0">
          <button
            onClick={() => toggleItem(item.props.id)}
            className="flex justify-between items-center w-full p-4 text-left text-lg font-medium text-gray-700 hover:bg-gray-50 focus:outline-none"
          >
            {item.props.title}
            <span>{openItemId === item.props.id ? '−' : '+'}</span>
          </button>
          {openItemId === item.props.id && (
            <div className="p-4 bg-gray-50">
              {/* Server-rendered content is passed here */}
              {item.props.children}
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

// Dummy component for structure, implicitly a Server Component
export function ServerAccordionItem({ title, id, children }: AccordionItemProps) {
  return <>{children}</>; // Just passes its children through
}

And how it's used in a Server Component:

app/faq/page.tsx
// app/faq/page.tsx
import { ClientAccordion, ServerAccordionItem } from '@/components/ClientAccordion';
import { Suspense } from 'react';

async function getFAQAnswer(questionId: string) {
  await new Promise(resolve => setTimeout(resolve, 300)); // Simulate DB fetch
  switch (questionId) {
    case 'shipping':
      return 'We offer standard and express shipping options. Standard shipping usually takes 3-5 business days. This answer is fetched from the server.';
    case 'returns':
      return 'You can return items within 30 days of purchase. Please see our full return policy for details. This policy text is also server-rendered.';
    case 'payment':
      return 'We accept all major credit cards, PayPal, and Apple Pay. Secure payment processing is handled on the server.';
    default:
      return 'No answer found for this question.';
  }
}

// Server Component for an FAQ Answer Panel
async function FAQAnswerPanel({ questionId }: { questionId: string }) {
  const answer = await getFAQAnswer(questionId);
  return (
    <div className="text-gray-800">
      <p>{answer}</p>
      <p className="mt-2 text-sm text-gray-600">Answer for `{questionId}` rendered by the server.</p>
    </div>
  );
}

export default function FAQPage() {
  return (
    <main className="container mx-auto p-6">
      <h1 className="text-3xl font-bold mb-6">Frequently Asked Questions</h1>
      
      <ClientAccordion>
        <ServerAccordionItem title="What are your shipping options?" id="shipping">
          <Suspense fallback={<div>Loading shipping info...</div>}>
            <FAQAnswerPanel questionId="shipping" />
          </Suspense>
        </ServerAccordionItem>

        <ServerAccordionItem title="How do I return an item?" id="returns">
          <Suspense fallback={<div>Loading returns policy...</div>}>
            <FAQAnswerPanel questionId="returns" />
          </Suspense>
        </ServerAccordionItem>

        <ServerAccordionItem title="What payment methods do you accept?" id="payment">
          <Suspense fallback={<div>Loading payment info...</div>}>
            <FAQAnswerPanel questionId="payment" />
          </Suspense>
        </ServerAccordionItem>
      </ClientAccordion>
    </main>
  );
}

Again, ClientAccordion.tsx is lean, handling only the openItemId state and the toggle function. The actual FAQ answers are fetched and rendered by FAQAnswerPanel on the server, keeping the client bundle focused on interactivity.

Beyond Basic UI: Modals and Sticky Layouts

The Donut Composition pattern extends to more complex UI elements like modal dialogs and sticky sidebars.

Example 3: Modal Dialogs with Server-Rendered Content

A modal often displays detailed information: a product quick-view, a user profile editor, or terms and conditions. If this content is heavy, you don't want to bundle it with your modal's client-side open/close logic.

components/ClientModal.tsx
// components/ClientModal.tsx
'use client';

import React, { useState, type ReactNode, useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';

interface ClientModalProps {
  triggerButtonText: string;
  title: string;
  children: ReactNode; // Server-rendered content for the modal body
}

export function ClientModal({ triggerButtonText, title, children }: ClientModalProps) {
  const [isOpen, setIsOpen] = useState(false);
  const modalRef = useRef<HTMLDivElement>(null);

  // Close modal on escape key press
  useEffect(() => {
    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        setIsOpen(false);
      }
    };
    if (isOpen) {
      document.addEventListener('keydown', handleEscape);
    }
    return () => {
      document.removeEventListener('keydown', handleEscape);
    };
  }, [isOpen]);

  // Close modal when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (modalRef.current && !modalRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };
    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen]);

  if (!isOpen) {
    return (
      <button 
        onClick={() => setIsOpen(true)} 
        className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
      >
        {triggerButtonText}
      </button>
    );
  }

  // Use createPortal to render the modal outside the main DOM flow
  // This is a client-side API, so it must be within a 'use client' component
  return createPortal(
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div 
        ref={modalRef} 
        className="bg-white rounded-lg shadow-xl max-w-lg w-full p-6 relative"
      >
        <h2 className="text-2xl font-bold mb-4">{title}</h2>
        <button 
          onClick={() => setIsOpen(false)} 
          className="absolute top-4 right-4 text-gray-600 hover:text-gray-900 text-2xl"
        >
          &times;
        </button>
        <div className="modal-body">
          {/* Server-rendered content goes here */}
          {children}
        </div>
      </div>
    </div>,
    document.body // Render the modal directly into the body
  );
}

And the usage with server-rendered product details:

app/dashboard/page.tsx
// app/dashboard/page.tsx
import { ClientModal } from '@/components/ClientModal';
import { Suspense } from 'react';

interface Product {
  id: string;
  name: string;
  price: number;
  description: string;
}

// Mock database call
async function getProductDetails(productId: string): Promise<Product> {
  await new Promise(resolve => setTimeout(resolve, 700)); // Simulate network delay
  return {
    id: productId,
    name: `Product ${productId.toUpperCase()}`,
    price: parseFloat((Math.random() * 100 + 10).toFixed(2)),
    description: `This is a highly detailed description for Product ${productId.toUpperCase()}. It includes many technical specifications, marketing fluff, and user testimonials, all generated and rendered on the server. Imagine this is hundreds of lines of rich text.`,
  };
}

// Server Component for Product Details
async function ServerProductDetails({ productId }: { productId: string }) {
  const product = await getProductDetails(productId);
  return (
    <div className="p-4 bg-blue-50 rounded-lg">
      <h3 className="text-xl font-semibold mb-2">{product.name}</h3>
      <p className="text-lg text-blue-700 mb-3">${product.price.toFixed(2)}</p>
      <p className="text-gray-700">{product.description}</p>
      <p className="mt-4 text-sm text-gray-600">Product details for `{productId}` fetched and rendered on the server.</p>
    </div>
  );
}

export default function DashboardPage() {
  return (
    <main className="container mx-auto p-6">
      <h1 className="text-3xl font-bold mb-6">Dashboard Overview</h1>
      
      <p className="mb-4">This is some client-side content on your dashboard.</p>

      <ClientModal triggerButtonText="View Product A Details" title="Product A Information">
        {/* The ServerProductDetails component is rendered on the server
            and passed as children to ClientModal. */}
        <Suspense fallback={<div>Loading product details...</div>}>
          <ServerProductDetails productId="product-a" />
        </Suspense>
      </ClientModal>

      <div className="mt-8">
        <ClientModal triggerButtonText="View Product B Details" title="Product B Information">
          <Suspense fallback={<div>Loading product details...</div>}>
            <ServerProductDetails productId="product-b" />
          </Suspense>
        </ClientModal>
      </div>

      <p className="mt-8">More dashboard content here.</p>
    </main>
  );
}

The ClientModal component handles the isOpen state, the createPortal API (which must be client-side), and basic accessibility. The actual product details (ServerProductDetails) are fetched and rendered by the server. This keeps the initial bundle for the dashboard page extremely small, as the heavy product data is never part of the client JavaScript. When the modal opens, the pre-rendered HTML for the product details is already there, ready to be displayed.

Architecture Note

[!NOTE] The createPortal API is a client-side React feature. This means any component using createPortal must be a use client component. Donut Composition allows you to portal a client component around server-rendered content, effectively moving the server content to a different part of the DOM while maintaining its server-rendered nature.

Example 4: Sticky Sidebars with Dynamic Server Content

A common pattern is a sticky sidebar for navigation or recommendations. The stickiness and perhaps some collapse/expand logic require client-side JavaScript. However, the content inside the sidebar (e.g., personalized recommendations, a complex user menu) is often best generated on the server.

components/ClientStickySidebar.tsx
// components/ClientStickySidebar.tsx
'use client';

import React, { useState, useEffect, type ReactNode } from 'react';

interface ClientStickySidebarProps {
  children: ReactNode; // Server-rendered content for the sidebar
  widthClass?: string;
}

export function ClientStickySidebar({ children, widthClass = 'w-64' }: ClientStickySidebarProps) {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [isSticky, setIsSticky] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      // Example: make sticky after scrolling 100px down
      setIsSticky(window.scrollY > 100); 
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  const sidebarClasses = `
    fixed top-0 left-0 h-full bg-gray-800 text-white p-4 
    transition-all duration-300 ease-in-out z-40
    ${isCollapsed ? 'w-16' : widthClass}
    ${isSticky ? 'shadow-lg' : ''}
  `;

  return (

7. How to Audit Your RSC Client Bundle in 5 Minutes

Even with React Server Components (RSCs), client bundle size can still explode. The use client directive is powerful, but it's also a boundary. Anything imported into a use client component, and its entire dependency tree, gets shipped to the browser. This includes libraries you might think are server-only. Finding these hidden leaks is crucial for performance.

We need a systematic way to audit our client bundles. This isn't just about initial load times. Smaller bundles mean less memory usage on the client, faster parse times, and quicker hydration. It impacts every user interaction.

Tracking Down Client-Side Bloat with next/bundle-analyzer

The first tool in your arsenal should be @next/bundle-analyzer. It gives you a visual treemap of your client-side JavaScript bundles. This helps you quickly spot the largest contributors to your client-side payload. It's like an X-ray for your application's client-side dependencies.

First, install it in your project:

terminal
npm install --save-dev @next/bundle-analyzer
# or
yarn add --dev @next/bundle-analyzer

Next, configure Next.js to use it. You'll modify your next.config.js file. This setup tells Next.js to run the analyzer when you build your application with a specific environment variable.

next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true', // Only run analyzer when ANALYZE=true
});

/** @type {import('next').NextConfig} */
const nextConfig = {
  // Your other Next.js configurations go here
  // For example:
  // experimental: {
  //   serverActions: true,
  //   serverComponentsExternalPackages: ['my-server-only-lib'],
  // },
};

module.exports = withBundleAnalyzer(nextConfig); // Wrap your config with the analyzer

Now, run a production build with the ANALYZE environment variable set:

terminal
ANALYZE=true npm run build
# or
ANALYZE=true yarn build

After the build completes, your browser will automatically open several tabs. Each tab displays an interactive treemap. You'll see one for each client-side entry point (e.g., _app.js, _error.js, and your client components). The larger the box on the treemap, the more code it contributes to that specific bundle.

Interpreting the Treemaps:

  • Identify large client components: Look for your own components that take up significant space. If a component is marked use client and imports a heavy library, that library will show up here.
  • Spot third-party library bloat: Often, a single large library like lodash, moment, or a charting library (e.g., recharts, chart.js) can dominate a bundle. If these are only used in a small part of your UI, you might need to reconsider their placement or use dynamic imports.
  • Unintended server-side leaks: Sometimes, a library you thought was server-only (e.g., a database client, a large utility belt for server actions) gets pulled into a use client boundary. This is a common "boundary trap." The official React Server Components Reference on react.dev explains these boundaries well.

For example, imagine you have a <DashboardChart /> component marked use client. If it imports a full charting library, you'll see that library's entire footprint in the client bundle. A better approach might be to fetch the chart data on the server, then pass only the necessary data to a lightweight client chart component, or even render a static image of the chart on the server.

Diving Deeper with Webpack/Turbopack Stats

While next/bundle-analyzer is great for a visual overview, sometimes you need more granular data. It's built on top of Webpack's stats output. You can generate these raw stats directly for a deeper dive. Next.js uses Webpack for builds by default, though Turbopack is an experimental option for faster compilation. For consistency, we'll focus on Webpack stats, which are universally understood.

To generate a raw Webpack stats file, you can modify your build command:

terminal
next build --json > webpack-stats.json

This command will output a large JSON file named webpack-stats.json. This file contains detailed information about every module, chunk, and dependency in your build. It's not human-readable on its own.

You can then use tools like webpack-bundle-analyzer (the CLI version, not the Next.js wrapper) to visualize this JSON:

terminal
npx webpack-bundle-analyzer webpack-stats.json

This will give you a similar treemap interface but with potentially more configuration options and direct access to the raw data.

What to look for in raw stats:

  • Module sizes: Identify individual files or modules contributing heavily.
  • Chunk composition: See exactly which modules end up in which client-side chunks. This helps confirm if a server-only module has accidentally slipped into a client chunk.
  • Duplicate modules: Sometimes different versions of the same library get bundled. The stats file can reveal this.

This level of detail is invaluable when you've identified a large chunk with the visual analyzer but need to pinpoint the exact module causing the bloat. It helps you trace the import path that led to the unwanted dependency.

Engineering Tip

[!TIP] When reviewing webpack-stats.json, pay close attention to the chunks array. Each object in this array represents a client-side bundle. Within each chunk, you can inspect the modules array to see every file that was included. This is where you'll find the specific file paths of problematic server-side libraries leaking into your client.

Runtime Analysis with Chrome DevTools Coverage Tab

Build-time analysis tells you what could be shipped. Runtime analysis tells you what actually gets used by the browser. The Chrome DevTools Coverage tab is excellent for this. It highlights unused JavaScript and CSS. Even if a component is marked use client, it might import a large utility library, but only use one small function from it. The Coverage tab helps expose this.

Here’s how to use it:

  1. Open DevTools: In Chrome, right-click anywhere on your page and select "Inspect" or press Cmd+Option+I (Mac) / Ctrl+Shift+I (Windows/Linux).
  2. Navigate to Coverage Tab: Open the Command Menu (Cmd+Shift+P or Ctrl+Shift+P), type "Coverage", and select "Show Coverage".
  3. Start Recording: Click the "Record" button (a circle icon) in the Coverage tab.
  4. Interact with Your App: Browse your application, click buttons, open modals, and interact with all the features. This ensures the browser executes the code paths you want to analyze.
  5. Stop Recording: Click the "Stop" button (a square icon).

The Coverage tab will then display a list of all loaded JavaScript and CSS files, showing the percentage of code that was used versus unused. Red bars indicate unused bytes, while green bars show used bytes.

What to look for:

  • High percentage of unused JavaScript: This is your primary target. If a client bundle has 60-70% unused JavaScript, it means you're shipping a lot of dead code.
  • Large files with low usage: Sort by size or percentage. A 200KB JavaScript file with only 10% usage is a major optimization opportunity.
  • Specific library files: You can drill down into individual files to see which functions or sections of code were not executed.

This is especially helpful for identifying:

  • Unused utility functions: You might import an entire library like lodash but only use _.get. Tree-shaking often helps, but not always perfectly, especially with older libraries or complex imports.
  • Conditional code paths not taken: Features only accessible after certain user interactions might load code that's never used by most users.
  • Legacy code: Old features that are no longer active but still part of the bundle.

The Coverage tab complements build-time analysis. next/bundle-analyzer shows you what is in the bundle. The Coverage tab shows you what fraction of that bundle is actually executed by the browser during a typical user session. If you have a use client component that only renders after a complex user flow, its code might be shipped immediately but only used by a fraction of users. This is a strong case for dynamic imports using React.lazy() and Suspense. You can learn more about Suspense and streaming boundaries in our guide on Eliminating Request Waterfalls in React Server Components with Parallel Streaming & Suspense.

Proactive CI/CD Bundle Budgeting

Auditing manually is good, but it's reactive. The best approach is to prevent bundle bloat from happening in the first place, or at least catch it early. This is where CI/CD bundle budgeting comes in. You set limits on your client-side bundle sizes, and your CI pipeline automatically fails pull requests (PRs) that exceed those limits.

This creates a "gate" for new code. No one can accidentally merge a change that significantly increases your client bundle size without being flagged.

How to implement bundle budgets:

  1. Establish a Baseline: Run @next/bundle-analyzer or generate Webpack stats on your current production build. Document the sizes of your main client chunks. This is your starting point.
  2. Set Budgets: Define acceptable maximum sizes for your critical client bundles (e.g., main.js, framework.js, specific page bundles). You can set hard limits or allow for a small percentage increase.
  3. Integrate into CI: Use a tool that can parse your build stats and compare them against your defined budgets.

A common tool for this is next-bundle-analyzer itself, which can be configured to run in CI and output a report or even fail the build. Alternatively, you can write custom scripts that parse the webpack-stats.json file.

Here's a conceptual example of a CI script that might check bundle sizes:

ci-bundle-check.sh
#!/bin/bash

# Define your bundle size limits in KB
MAX_MAIN_JS=200
MAX_FRAMEWORK_JS=100
MAX_PAGE_BUNDLE=150

echo "Building project for bundle analysis..."
ANALYZE=true npm run build || { echo "Build failed!"; exit 1; }

echo "Analyzing bundle sizes..."

# Example: Extract main.js size (this is simplified, actual parsing is more complex)
# In a real scenario, you'd parse the generated stats.json or the analyzer's output.
# For demo, let's assume `next-bundle-analyzer` provides a text summary or a JSON artifact.
MAIN_JS_SIZE=$(grep "main.js" .next/analyze/client.json | awk '{print $NF}' | sed 's/KB//') # Placeholder

if (( $(echo "$MAIN_JS_SIZE > $MAX_MAIN_JS" | bc -l) )); then
  echo "ERROR: main.js bundle size ($MAIN_JS_SIZE KB) exceeds budget of $MAX_MAIN_JS KB!"
  exit 1
else
  echo "main.js bundle size ($MAIN_JS_SIZE KB) is within budget."
fi

# Add checks for other critical bundles like framework.js or specific page bundles
# ...

echo "Bundle size checks passed."
exit 0

This script is illustrative. In practice, you'd use a more robust parsing mechanism, possibly a dedicated CI reporter for next-bundle-analyzer or a library like webpack-bundle-size-analyzer to automate the comparison. The key is to make this check part of your PR workflow.

Tool Comparison for Bundle Auditing:

Feature@next/bundle-analyzerWebpack/Turbopack Raw Stats (--json)Chrome DevTools Coverage TabCI Bundle Budget Scripts
PurposeVisual build-time overviewDetailed build-time dataRuntime code usageAutomated size enforcement
OutputInteractive treemapsLarge JSON fileVisual usage percentagesPass/Fail in CI
GranularityModerate (chunk/module level)High (individual module paths)High (line-by-line usage)Configurable (chunk/total size)
Best ForInitial bloat identificationDeep dependency tracingFinding dead code in usePreventing regressions
EffortLow setup, quick visual scanMedium (parsing required)Medium (manual interaction)Medium setup, low maintenance
RSC FocusIdentifies use client leaksPinpoints exact server module leaksShows actual client code usePrevents new use client bloat

Implementing these tools and processes ensures that your client bundles remain lean. It's an ongoing battle, but a necessary one for a fast user experience. Remember, every kilobyte counts, especially on mobile networks or for users with slower connections. Proactive auditing and budgeting are key to maintaining a high-performance application built with React Server Components.

8. Quick Reference Cheat Sheet & Frequently Asked Questions

Understanding the boundary between React Server Components (RSCs) and Client Components is critical. It determines where your code runs, what resources it can access, and how much JavaScript your users download. Mismanaging this boundary is a common source of performance issues and unexpected behavior. This chapter provides a clear reference to help you navigate these distinctions effectively.

Think of it like designing a building. Server Components are the foundation, walls, and roof – fixed structures built at the factory. Client Components are the interactive elements inside: light switches, thermostats, or a smart display. You wouldn't put the entire building's structural plans into every light switch, just as you shouldn't send server-side logic to the browser.

The Server vs. Client Boundary: A Core Distinction

The 'use client' directive is more than just a flag; it's a declaration. When you mark a file with 'use client', you're telling React and your bundler: "This component, and everything it imports, needs to be sent to the browser." This has profound implications for bundle size, security, and performance. Conversely, files without 'use client' are Server Components by default. They run only on the server, leveraging Node.js APIs and never reaching the client's JavaScript bundle.

This distinction allows you to build highly performant applications. For instance, data fetching logic that hits your database, like retrieving product details from a PostgreSQL or Supabase instance, can stay entirely on the server. Only the result of that data fetch, the plain data, is sent to the client. This keeps sensitive credentials off the user's device and reduces the JavaScript payload. You can learn more about how this impacts database choices in our PostgreSQL vs. Supabase Architecture Benchmark.

Server vs. Client Boundary Cheat Sheet

This table summarizes the key differences and capabilities of Server and Client Components. Use it as a quick reference when deciding where to place your logic.

FeatureServer Components (Default)Client Components ('use client')
Execution EnvironmentServer (Node.js runtime)Browser (User's device)
Access to APIsFile system (fs), database (pg, ORMs), environment variables (process.env), server-only packages.Browser DOM (window, document), browser APIs (localStorage, navigator), client-side libraries.
StateNo React useState or useReducer. Data is fetched once per request.Full access to useState, useReducer, useContext. Manages interactive UI state.
EffectsNo useEffect, useLayoutEffect. No client-side lifecycle.Full access to useEffect, useLayoutEffect. Manages side effects in the browser.
Event HandlersNo direct browser event handlers (onClick, onChange). Can pass server actions.Full access to browser event handlers (onClick, onChange, onSubmit).
Bundle SizeZero JavaScript added to the client bundle for the component's code. Only serialized JSX is sent.Component's code is part of the client bundle. Imports increase bundle size.
Data FetchingDirect database queries, API calls using fetch (server-side).fetch (client-side), SWR, React Query. Typically fetches from API routes.
DirectivesNo directive needed. Implicitly a Server Component.Requires 'use client' at the top of the file.
Interactive UICannot handle user interaction directly.Essential for interactive UI elements (forms, buttons, modals).
Context APICannot use useContext directly to read context. Can provide context.Can use useContext to read context. Can also provide context.
SecurityIdeal for sensitive logic (API keys, database queries). Keeps secrets off the client.Should not contain sensitive logic or secrets.
RenderingRenders to HTML on the server. Can stream with Suspense.Hydrates on the client from server-generated HTML. Renders client-side updates.

Managing the Boundary with Props and Server Actions

The key to effective RSC architecture is understanding how to pass data and functionality across this boundary without bloating your client bundle or sacrificing interactivity. You can pass Server Components as props to Client Components, and you can invoke server-side functions from Client Components using 'use server'.

Consider a ProductCard component. The card's display logic and initial data fetch (product name, price, image URL) can be a Server Component. But if the card needs an "Add to Cart" button that updates local state or interacts with a shopping cart API on the client, that button must be a Client Component.

Here's how you might structure this, passing a Server Component (or parts of it) into a Client Component:

app/products/[id]/ProductDetails.tsx
// This file is a Server Component by default.
import { getProductById } from '@/lib/data-access';
import { AddToCartButton } from './AddToCartButton'; // This is a Client Component

interface ProductDetailsProps {
  productId: string;
}

export async function ProductDetails({ productId }: ProductDetailsProps) {
  // Data fetching happens ONLY on the server
  const product = await getProductById(productId);

  if (!product) {
    return <p>Product not found.</p>;
  }

  return (
    <div className="max-w-md mx-auto p-4 bg-white shadow-lg rounded-lg">
      <h1 className="text-3xl font-bold mb-2">{product.name}</h1>
      <p className="text-gray-700 text-lg mb-4">${product.price.toFixed(2)}</p>
      <img src={product.imageUrl} alt={product.name} className="w-full h-64 object-cover rounded-md mb-4" />
      <p className="text-gray-600 mb-6">{product.description}</p>
      {/*
        This is the crucial part: AddToCartButton is a Client Component.
        It receives product.id and product.name as props.
        The AddToCartButton itself handles client-side state for quantity,
        and uses a 'use server' action to update the cart on the backend.
        The server component renders the client component, but only its props are serialized.
      */}
      <AddToCartButton productId={product.id} productName={product.name} />
    </div>
  );
}

// Dummy data access layer for illustration
// This would typically interact with a database
// ts:lib/data-access.ts
export async function getProductById(id: string) {
  // Simulate a database call
  await new Promise(resolve => setTimeout(resolve, 100)); // Simulate network latency
  const products = [
    { id: '1', name: 'Wireless Headphones', price: 199.99, description: 'Premium sound, noise-cancelling, 30-hour battery.', imageUrl: '/headphones.jpg' },
    { id: '2', name: 'Smartwatch', price: 249.00, description: 'Track your fitness, notifications, elegant design.', imageUrl: '/smartwatch.jpg' },
  ];
  return products.find(p => p.id === id);
}
app/products/[id]/AddToCartButton.tsx
'use client'; // This directive is essential: this component needs client-side interactivity

import { useState } from 'react';
import { addProductToCart } from '@/lib/actions'; // This will be a 'use server' action

interface AddToCartButtonProps {
  productId: string;
  productName: string;
}

export function AddToCartButton({ productId, productName }: AddToCartButtonProps) {
  const [quantity, setQuantity] = useState(1);
  const [isAdding, setIsAdding] = useState(false);
  const [message, setMessage] = useState('');

  const handleAddToCart = async () => {
    setIsAdding(true);
    setMessage('');
    try {
      // Call the server action directly from the client component
      // This is a network request, but the logic runs on the server.
      await addProductToCart(productId, quantity);
      setMessage(`${quantity}x ${productName} added to cart!`);
      setQuantity(1); // Reset quantity after adding
    } catch (error) {
      console.error('Failed to add to cart:', error);
      setMessage('Failed to add to cart. Please try again.');
    } finally {
      setIsAdding(false);
    }
  };

  return (
    <div className="flex items-center space-x-4">
      <input
        type="number"
        min="1"
        value={quantity}
        onChange={(e) => setQuantity(Number(e.target.value))}
        className="w-20 p-2 border border-gray-300 rounded-md text-center"
        aria-label="Quantity"
      />
      <button
        onClick={handleAddToCart}
        disabled={isAdding}
        className="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
      >
        {isAdding ? 'Adding...' : 'Add to Cart'}
      </button>
      {message && <p className="text-sm mt-2">{message}</p>}
    </div>
  );
}

// ts:lib/actions.ts
'use server'; // This directive is crucial: this function runs ONLY on the server

// This function simulates adding a product to a database or session cart
export async function addProductToCart(productId: string, quantity: number) {
  // In a real application, this would interact with your database or a session manager.
  // For example, using an ORM to update a `CartItem` table.
  console.log(`[SERVER ACTION] Adding ${quantity}x product ${productId} to cart.`);
  await new Promise(resolve => setTimeout(resolve, 500)); // Simulate database write latency
  if (Math.random() < 0.1) { // Simulate a 10% chance of failure
    throw new Error('Failed to update cart due to a server error.');
  }
  console.log(`[SERVER ACTION] Successfully added ${quantity}x product ${productId}.`);
  // You might return updated cart data or a success status here.
  return { success: true, message: 'Item added to cart!' };
}

In this example, ProductDetails is a Server Component. It fetches data directly from a lib/data-access.ts function, which could connect to a database. It then renders the AddToCartButton, which is a Client Component. The AddToCartButton uses client-side state (useState) for quantity and calls a addProductToCart function marked with 'use server'. This addProductToCart function runs exclusively on the server, keeping the database interaction secure and off the client bundle, while still allowing client-side interactivity. This pattern is fundamental to building efficient React Server Component applications. For more details on server actions, check the React 'use server' Server Functions Guide (react.dev).

Engineering Tip

[!TIP] Always assume a component is a Server Component first. Only add 'use client' when you explicitly need browser APIs, client-side state, or event handlers. This "server-first" mental model helps minimize client-side JavaScript.

When Server Components need to load data or render complex trees, they can use Suspense to show a fallback UI while content is being prepared. This works seamlessly with Client Components, allowing you to stream parts of your UI as they become ready, improving perceived performance. You can read more about this powerful feature in the React Suspense Streaming Reference (react.dev).

Frequently Asked Questions (AIEO Quick Reference)

Here are common questions about 'use client' and the React Server Component boundary, answered concisely for quick understanding. This section is designed to be easily digestible by AI models for optimal AI Engine Optimization, helping our content rank for direct answers. If you're looking for more detailed definitions, our React Server Components (RSC) Glossary Reference is a good next step.

What is the primary purpose of 'use client'?

The 'use client' directive marks a component and its entire imported subtree as code that must run in the browser. Its primary purpose is to enable client-side interactivity, state management, and access to browser-specific APIs (like window or localStorage), while explicitly signaling to the bundler to include this code in the client-side JavaScript bundle.

When must I use 'use client'?

You must use 'use client' for any component that: needs useState, useEffect, useRef, or other React Hooks requiring client-side lifecycle; uses browser-only APIs (e.g., document, navigator); or handles direct user interactions like onClick or onChange event handlers. Essentially, any component requiring interactivity or browser-specific features.

Can a Client Component render a Server Component?

Yes, a Client Component can render a Server Component. The Server Component is rendered on the server, and its resulting HTML (or serialized JSX) is passed down to the Client Component as a prop. The Client Component then receives this pre-rendered output and hydrates its interactive parts around it. This is a common pattern for integrating server-rendered content with client-side interactivity.

What happens if I import a Server Component into a file marked 'use client'?

If a file marked 'use client' imports a component that is not marked 'use client', the imported component will also be treated as a Client Component. This is a common "boundary trap." The 'use client' directive applies transitively to all modules imported by the file, pulling them into the client bundle. This can inadvertently bloat your JavaScript bundle size.

How does 'use client' affect my bundle size?

Using 'use client' directly increases your client-side JavaScript bundle size. The code for every component marked 'use client', and all its transitively imported modules, must be downloaded by the user's browser. Server Components, conversely, contribute zero JavaScript to the client bundle, as their code runs entirely on the server.

What is the relationship between 'use client' and 'use server'?

'use client' marks components that run in the browser for interactivity. 'use server' marks functions that run exclusively on the server, even when called from a Client Component. They are complementary: a Client Component might call a 'use server' function to perform a secure backend operation without sending server logic to the client. Refer to the React 'use client' Directive Specification (react.dev) for more.

Can I use React Context with Server Components?

Server Components cannot read context values directly using useContext because context is primarily for client-side state management and re-renders. However, a Server Component can provide context. This context is then accessible by Client Components rendered within its subtree, allowing for global state management for the client-side parts of your application.

Does 'use client' impact SEO?

Directly, no. Google and other search engines can render JavaScript. However, indirectly, it can. If excessive 'use client' usage leads to a very large JavaScript bundle and slow page load times, it can negatively impact user experience and, consequently, SEO. Prioritizing Server Components where possible leads to faster initial page loads and better user experience, which is beneficial for SEO. Tools like our Free SEO & AIEO Schema Generator can help optimize your content further.

Verified Engineering References & Further Reading

Official Specifications & Primary Documentation

Key Takeaways

  • Pushing 'use client' to the smallest interactive leaf components prevents entire module graphs from leaking into the browser bundle.
  • The Donut Composition pattern lets you wrap server-rendered content with minimal client wrappers, keeping bundle size down.
  • A quick audit of imports in 'use client' files can reveal hidden dependencies that inflate bundle size by hundreds of kilobytes.
Mubashir Arham
Written & Verified byLast Verified: 2026-08-09

Mubashir Arham

Founder & Principal Systems Architect

Founder, CEO, and Principal Full-Stack & AI Systems Architect at FutureStack (futurestack.online). Writing deeply researched monographs on AI inference, distributed systems, and modern web runtimes.

Read all publications by Mubashir Arham
Related Engineering Workbench

Free Client-Side AI & Systems Calculators

Size GPU KV-cache VRAM, estimate LLM token costs, audit JWTs, or generate Zod schemas with zero server uploads.

Explore Free Developer Tools
Next in Track • Web & Edge Runtime

React Server Components Without Next.js: Using RSC with Vite, Waku, and React Router 7

You don't need Next.js to use React Server Components anymore. Explore how the Vite Environment API, Waku, and React Router 7 let you run RSC on any Node, Bun, Cloudflare, or Docker server.

Read Next Investigation
Interactive Practice • Free No Login

Test this topic live in Fusta AI Code Canvas

Ask follow-up questions or generate a working React, TypeScript, or Python example based on “The "use client" Boundary Trap: 7 React Server Component Mistakes That Bloat Your Bundle”.

Deliberations (0)

Moderated • Anti-Spam & Link Safety Active

Contribute your perspective

Loading discussion thread...