🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

React Server Components: Boundaries and Streaming

React AdvancedđŸŸĸ Free Lesson

React Server Components change the unit of work rather than the syntax. A component marked for the server runs only during the request on a Node or edge runtime, can read the database directly, and never ships a single byte of its code to the browser. A component marked for the client runs in both places as usual, but it can now receive server-only data as plain props instead of fetching it again after mount. The design skill is choosing where the boundary sits, because moving it in the wrong direction costs either bundle size or interactivity.

âš ī¸The boundary is contagious

Importing a server module from a client component is a build error, and passing a function across the boundary is not allowed unless it is a server action. Every import on the client side pulls that module and its dependencies into the browser bundle, which is why a single careless import of a date library or an SDK can undo the whole benefit.

One tree, two runtimes

During a request the framework renders the server portion of the tree into a serialized form of the component tree, not into HTML strings of the final markup. That representation travels to the client, where it hydrates the client portion while the server portion is discarded after contributing its output. The result is that the browser receives the rendered UI for server components and the actual JavaScript only for client components.

This is different from server-side rendering in the classic sense. With SSR, the server produces HTML that the client then has to re-execute to attach interactivity, and the full component code for everything on the page is still downloaded. With server components, there is nothing to re-execute for the server half: it rendered once, produced markup, and its code is never requested again.

What each side is allowed to do

Knowing the rules by heart prevents most boundary mistakes. The practical distinction is less about syntax than about capabilities that only exist in one environment.

CapabilityServer componentClient component
Read files, environment secrets and the databaseYes, directlyNo, must call an endpoint
Use hooks such as useState and useEffectNoYes
Access browser APIs, event listeners and localStorageNoYes
Add code to the client bundleNeverAlways
Render as the default in the app routerYesRequires the use client directive
Import npm packages that assume a DOMOnly server-safe onesYes
Accept a serializable prop from the other sideYesYes

A useful habit is to write components as server components by default and add the client directive only when the component genuinely needs state, effects or event handlers. Each directive you add is a promise that the code behind it is worth shipping, so treat it like a decision with a cost rather than a boilerplate line.

Fetching data without the effect dance

The familiar pattern of useEffect with a loading flag, a cancelled boolean and an error branch disappears on the server, because the component can await its data before rendering. Loading states are then expressed with Suspense boundaries rather than boolean state, and each boundary streams independently.

// app/products/[id]/page.js — server component by default
import { Suspense, notFound } from 'react';
import { db } from '@/lib/db';
import { AddToCartButton } from './add-to-cart-button';
import { ReviewList } from './review-list';
import { ProductSkeleton, ReviewSkeleton } from './skeletons';

async function ProductDetails({ id }) {
  const product = await db.product.findUnique({
    where: { id },
    include: { manufacturer: true },
  });

  if (!product) notFound();

  return (
    <article>
      <h1>{product.name}</h1>
      <p>By {product.manufacturer.name}</p>
      <p>${product.price}</p>
      <AddToCartButton productId={product.id} />
    </article>
  );
}

export default function ProductPage({ params }) {
  return (
    <div className="grid">
      <Suspense fallback={<ProductSkeleton />}>
        <ProductDetails id={params.id} />
      </Suspense>
      <Suspense fallback={<ReviewSkeleton />}>
        <ReviewList productId={params.id} />
      </Suspense>
    </div>
  );
}

Two properties of this code are worth noticing. The database call happens during render, which would be a cardinal sin in a client component and is normal here, because the server component renders exactly once per request and can never re-run from a state update. And the two Suspense boundaries are independent, so a slow review query does not hold back the product name and price that arrived in milliseconds.

Server actions for writes

Mutations need a way back to the server without an API route you write by hand. A server action is an async function marked with the use server directive, callable from a client component or a form, validated, and automatically typed when you generate types for the client. The browser receives a reference rather than the function body.

'use server';

import { revalidatePath } from 'next/cache';
import { db } from '@/lib/db';

export async function addItem(formData) {
  const productId = formData.get('productId');
  const quantity = Number((formData.get('quantity') || 1));

  if (!Number.isInteger(quantity) || quantity < 1 || quantity > 20) {
    return { error: 'Quantity must be between 1 and 20' };
  }

  await db.cart.upsert({
    where: { userId_productId: { userId: currentUser.id, productId } },
    create: { userId: currentUser.id, productId, quantity },
    update: { quantity: { increment: quantity } },
  });

  revalidatePath('/cart');
  return { ok: true };
}
'use client';

import { useActionState } from 'react';
import { addItem } from './actions';

export function AddToCartButton({ productId }) {
  const [state, formAction, pending] = useActionState(addItem, null);

  return (
    <form action={formAction}>
      <input type="hidden" name="productId" value={productId} />
      <input type="hidden" name="quantity" value="1" />
      <button disabled={pending}>
        {pending ? 'Adding...' : 'Add to cart'}
      </button>
      {state?.error && <p role="alert">{state.error}</p>}
    </form>
  );
}

The form is the important part. Because the action is wired through the form, it works before JavaScript loads, carries its own request body, and revalidates the route so the server-rendered list updates without a client-side fetch. useActionState exposes the returned value and the pending flag, which gives you the disabled state and error message that would otherwise require local state and manual error handling.

Streaming so slow queries do not block HTML

Time to first byte is dominated by whatever the server must finish before it can send anything. Streaming inverts that: the shell with the header, navigation and skeleton leaves immediately, and each Suspense boundary flushes its resolved subtree when its data arrives, preceded by a small inline script that swaps the placeholder for the real markup. The browser paints the page structure at once and fills in the slow regions as they complete.

The discipline this demands is that every boundary has a meaningful fallback of roughly the final shape. A spinner in a two hundred pixel box followed by a tall table causes layout shift that Core Web Vitals will penalize, so size skeletons to the content they replace and reserve space before the data lands.

Moving a component across the boundary

The migration path is mechanical once you know what to look for. Start with the leaf: find the smallest component that touches a browser API or owns user state, add the directive there, and let the build tell you what crossed the line. If a server-only helper is pulled into the bundle, extract it back behind a server entry point. If you find yourself wanting to pass a callback down, convert the parent to a client component only when every child beneath it genuinely needs interactivity.

The cost you are managing is total client bytes. A page where two hundred lines of server components render a catalogue, and only the add-to-cart button ships JavaScript, will beat a page where every row is interactive even though ninety percent of those rows are read-only. That ratio is the number to watch as a feature grows.

Common Mistakes

Adding the client directive to a whole route because one leaf component needs a click handler

Fix: Push the directive down to the smallest interactive leaf so the surrounding markup stays server-only.

Fetching on the server and then fetching the same data again in an effect after hydration

Fix: Pass the server result down as a prop, or let a client cache own the request instead of doing both.

Passing a plain callback or a class instance across the boundary

Fix: Serialize only primitives, plain objects and arrays; use a server action when you need to send a function the other way.

Giving every Suspense boundary a spinner of a different height than its content

Fix: Match the fallback to the final layout so streaming does not produce layout shift.

Best Practices

  • Write components as server components first and add the client directive only where state, effects or handlers are unavoidable
  • Give each slow data source its own Suspense boundary so one query cannot delay the whole document
  • Colocate data fetching with the component that renders it and let the framework deduplicate parallel requests
  • Audit the client bundle after each feature: every new import on the client side is a permanent cost

Key Takeaways

  • Server components render once per request, can read the database directly, and never add code to the browser bundle
  • The use client directive is contagious through imports, so keep it as deep in the tree as possible
  • Server actions replace hand-written API routes for mutations and work even before hydration completes
  • Streaming with per-section Suspense boundaries delivers the shell immediately and fills slow sections as they resolve
  • Pass data across the boundary as serializable props, and functions only through server actions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement