Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

React Server Components vs Client Components: When to Use Each

Does a single interactive button require moving an entire page into the browser? No. In Next.js App Router, the catalog and its data access can stay on the server while the browser receives the logic needed for interaction. A poorly placed boundary can inflate the JavaScript bundle, expose unnecessary data or invoke unavailable APIs. These React 19 and App Router examples show how to split responsibilities without confusing Server Components with SSR.

Published Written by Reading time 8 min read
On this page Contents: quick navigation between sections

Does use client disable server-side rendering?

app/catalog/page.tsx

import { QuantityPicker } from "./quantity-picker";

export default function CatalogPage() {
  return (
    <main>
      <h1>Catalog</h1>
      <p>Mechanical keyboard</p>
      <QuantityPicker />
    </main>
  );
}

app/catalog/quantity-picker.tsx

"use client";

import { useState } from "react";

export function QuantityPicker() {
  const [quantity, setQuantity] = useState(1);

  function increaseQuantity() {
    setQuantity((currentQuantity) => currentQuantity + 1);
  }

  return (
    <button type="button" onClick={increaseQuantity}>
      Quantity: {quantity}
    </button>
  );
}

A Server Component executes in a server environment or at build time. Its implementation is not needed in the browser bundle. A Client Component has executable browser code and can manage state, events and effects. App Router pages and layouts are Server Components by default. [1][3]

On the initial visit, Next.js uses the RSC payload and Client Components to prepare HTML. The browser uses RSC data to reconcile the tree and client JavaScript to hydrate interactive parts. use client does not turn off initial HTML rendering. In the catalog example, only the quantity picker needs state; the page and product description stay on the server. [2][3]

Where should the use client boundary go?

app/reports/page.tsx

import { ReportPanel } from "./report-panel";
import { ReportSummary } from "./report-summary";

export default function ReportsPage() {
  return (
    <ReportPanel>
      <ReportSummary />
    </ReportPanel>
  );
}

app/reports/report-panel.tsx

"use client";

import { useId, useState, type ReactNode } from "react";

type ReportPanelProps = {
  children: ReactNode;
};

export function ReportPanel({ children }: ReportPanelProps) {
  const [isOpen, setIsOpen] = useState(false);
  const contentId = useId();

  return (
    <section>
      <button
        type="button"
        aria-expanded={isOpen}
        aria-controls={contentId}
        onClick={() => setIsOpen((current) => !current)}
      >
        Report summary
      </button>
      <div id={contentId} hidden={!isOpen}>
        {children}
      </div>
    </section>
  );
}

app/reports/report-summary.tsx

import "server-only";

export function ReportSummary() {
  return <p>Orders processed: 42</p>;
}

A directive at the top of a file defines a module dependency boundary, not a blanket rule for every JSX descendant. Runtime imports reachable from client code may enter its bundle; TypeScript type-only imports are erased. A server-rendered element received as children is not automatically converted into a Client Component. [2]

The reports page constructs a panel on the server and passes a ReportSummary element into it. The panel only toggles visibility. server-only prevents accidental inclusion of the summary module in the client graph. The report is prepared even while the panel is closed: hiding it neither postpones data access nor enforces authorization. [3][4]

What data can cross the server-client boundary?

lib/public-product.ts

type ProductRecord = {
  id: string;
  name: string;
  priceInCents: number;
  supplierCostInCents: number;
};

export type PublicProduct = Pick<
  ProductRecord,
  "id" | "name" | "priceInCents"
>;

export function toPublicProduct(product: ProductRecord): PublicProduct {
  return {
    id: product.id,
    name: product.name,
    priceInCents: product.priceInCents,
  };
}

app/products/page.tsx

import "server-only";

import { toPublicProduct } from "../../lib/public-product";
import { PriceLabel } from "./price-label";

export default function ProductsPage() {
  const product = {
    id: "keyboard-1",
    name: "Keyboard",
    priceInCents: 12900,
    supplierCostInCents: 6400,
  };

  return <PriceLabel product={toPublicProduct(product)} />;
}

app/products/price-label.tsx

"use client";

import { useState } from "react";
import type { PublicProduct } from "../../lib/public-product";

type PriceLabelProps = {
  product: PublicProduct;
};

export function PriceLabel({ product }: PriceLabelProps) {
  const [showCents, setShowCents] = useState(false);
  const price = showCents
    ? `${product.priceInCents} cents`
    : new Intl.NumberFormat("en-US", {
        style: "currency",
        currency: "USD",
      }).format(product.priceInCents / 100);

  return (
    <button
      type="button"
      onClick={() => setShowCents((current) => !current)}
    >
      {product.name}: {price}
    </button>
  );
}

React supports values defined by its own serialization protocol, not just JSON. Date, Map, Set and Promise are examples. Arbitrary class instances and ordinary server functions are not valid props across this boundary; Server Function references are a special case. [2][5]

Pick narrows a compile-time contract but does not remove runtime properties. The explicit mapper in the example constructs an object without the supplier cost. Passing the full record and displaying only its price is not sufficient, because data passed to the client is accessible to its user. Real applications must also enforce access rights in the data layer before reading records. [4][10]

Why is window undefined despite use client?

app/preferences/time-zone.tsx

"use client";

import { useEffect, useState } from "react";

export function TimeZone() {
  const [timeZone, setTimeZone] = useState<string | null>(null);

  useEffect(() => {
    setTimeZone(Intl.DateTimeFormat().resolvedOptions().timeZone);
  }, []);

  return <p>Time zone: {timeZone ?? "Loading…"}</p>;
}

A Client Component can participate in initial rendering outside the browser. Reading window, localStorage or a local time zone during render can throw or create a difference between server HTML and the first client render. A typeof window guard does not solve mismatches if it changes the initial markup. [3][8]

The time-zone example starts with identical server and client state. An effect fills in the browser value after hydration. For a library that requires the DOM at import time, a dynamic import with ssr: false in a client module can be appropriate, at the cost of initial HTML for that part. [8][9]

How can data load without blocking the entire page?

app/orders/page.tsx

import { Suspense } from "react";
import { OrderList } from "./order-list";

type Order = { id: string; reference: string };

async function loadOrders(): Promise<Order[]> {
  // Demonstration data; replace with an authorized data-access function.
  return [{ id: "1", reference: "ORD-001" }];
}

export default function OrdersPage() {
  const ordersPromise = loadOrders();

  return (
    <main>
      <h1>Orders</h1>
      <Suspense fallback={<p>Loading orders…</p>}>
        <OrderList ordersPromise={ordersPromise} />
      </Suspense>
    </main>
  );
}

app/orders/order-list.tsx

"use client";

import { use, useState } from "react";

type Order = { id: string; reference: string };

type OrderListProps = {
  ordersPromise: Promise<Order[]>;
};

export function OrderList({ ordersPromise }: OrderListProps) {
  const orders = use(ordersPromise);
  const [query, setQuery] = useState("");
  const visibleOrders = orders.filter((order) =>
    order.reference.toLowerCase().includes(query.toLowerCase()),
  );

  return (
    <>
      <label>
        Filter orders
        <input
          value={query}
          onChange={(event) => setQuery(event.target.value)}
        />
      </label>
      <ul>
        {visibleOrders.map((order) => (
          <li key={order.id}>{order.reference}</li>
        ))}
      </ul>
    </>
  );
}

If a result is only needed for display, an async Server Component can read it directly. There is no need to create an extra endpoint solely for the application server to call itself. Start independent operations concurrently where appropriate; Suspense can separate a waiting region from the rest of the page. [1][7]

The orders example creates a promise on the server and reads it with use in a Client Component. Filtering happens locally once data arrives. The demonstration promise resolves immediately, so the fallback may never become visible. A rejected promise goes to an error boundary, not to Suspense itself. Filter and paginate large or sensitive datasets on the server before sending them to the client. [6][7][10]

Does use server make mutations secure?

app/settings/preference-policy.ts

export type Viewer = {
  id: string;
  canEditPreferences: boolean;
};

type SavePreference = (
  userId: string,
  density: "compact" | "comfortable",
) => Promise<void>;

export async function updateDensity(
  viewer: Viewer | null,
  value: unknown,
  savePreference: SavePreference,
): Promise<void> {
  if (!viewer?.canEditPreferences) {
    throw new Error("Forbidden");
  }

  if (value !== "compact" && value !== "comfortable") {
    throw new Error("Invalid density");
  }

  await savePreference(viewer.id, value);
}

app/settings/actions.ts (integration example)

"use server";

import { requireViewer, savePreference } from "@/lib/server/preferences";
import { updateDensity } from "./preference-policy";

export async function saveDensity(formData: FormData): Promise<void> {
  const viewer = await requireViewer();

  await updateDensity(viewer, formData.get("density"), savePreference);
}

app/settings/page.tsx

import { saveDensity } from "./actions";

export default function SettingsPage() {
  return (
    <form action={saveDensity}>
      <label>
        Density
        <select name="density" defaultValue="comfortable">
          <option value="comfortable">Comfortable</option>
          <option value="compact">Compact</option>
        </select>
      </label>
      <button type="submit">Save</button>
    </form>
  );
}

use server marks callable Server Functions, not Server Components. An exported Server Function used for mutations is an entry point that must verify identity, permissions and input on every invocation. Hiding a button does not protect the underlying operation. [4][5][10]

The settings example validates permitted values and writes using the authenticated viewer ID, not an ID supplied by the form. requireViewer and savePreference are integration points for a real session and database; authentication is not implemented here. Updating data used by other components may require refreshing or invalidating the relevant cache, depending on the framework configuration. [4][10]

How do you measure whether a boundary improves performance?

app/editor/editor-launcher.tsx

"use client";

import dynamic from "next/dynamic";
import { useState } from "react";

const Editor = dynamic(() => import("./editor"), {
  loading: () => <p>Loading editor…</p>,
  ssr: false,
});

export function EditorLauncher() {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <section>
      <button
        type="button"
        onClick={() => setIsOpen(true)}
        disabled={isOpen}
      >
        Open editor
      </button>
      {isOpen && <Editor />}
    </section>
  );
}

app/editor/editor.tsx

"use client";

import { useState } from "react";

export default function Editor() {
  const [text, setText] = useState("");

  return (
    <label>
      Notes
      <textarea
        value={text}
        onChange={(event) => setText(event.target.value)}
      />
    </label>
  );
}

Moving code to the server can reduce client JavaScript, but it does not guarantee better LCP or INP. Server work, RSC response size or navigation requests may increase. Compare the same route and data in production builds with cold and warm caches. Inspect JS and RSC transfers in Network, script execution and interaction latency in Performance. [3][9]

The editor example loads a module dynamically when opening the editor. This is a separate optimization from the Server/Client split; frameworks may perform their own prefetching. Measure the first opening as well as subsequent openings after the module has loaded. Do not move an interaction to the server simply to improve one transfer metric. [9]

Keep data access and non-interactive work on the server where appropriate, and place state and events within small client boundaries. Pass only necessary data and compose server-rendered children rather than importing server modules into client code. Authorize every mutation on the server. Let measured transfer, rendering and interaction costs determine the final boundary rather than counting use client directives.

Tools for this topic

React Server Components Client Components React Server Components Next.js SSR Hydration React Performance Server Functions Data Security

Frequently asked questions

Does a Client Component render only in the browser?

No. In Next.js it may contribute to initial server-rendered HTML and then hydrate in the browser. [3]

Can a Server Component be inside a Client Component?

Yes, if a server parent constructs the element and passes it as a prop such as children. Directly importing a server-only module into client code is different. [2][3]

Do Server Components replace APIs?

No. They can access server data directly, but public APIs, integrations and some interactions still need endpoints. [1][4]

Does use server guarantee security?

No. Each function must enforce authorization and validate its arguments. [5][10]

Sources and references

  1. React, Server Components↩1↩2↩3
  2. React, use client↩1↩2↩3↩4↩5
  3. Next.js, Server and Client Components↩1↩2↩3↩4↩5↩6↩7↩8↩9
  4. Next.js, Data Security↩1↩2↩3↩4↩5↩6
  5. React, use server↩1↩2↩3↩4
  6. React, use↩
  7. React, Suspense↩1↩2
  8. Next.js, Hydration Error↩1↩2
  9. Next.js, Lazy Loading↩1↩2↩3
  10. Next.js, Authentication↩1↩2↩3↩4↩5↩6

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning