Skip to main content
CodingMarble

Web development

React Server Components Explained with Examples

React Server Components render on the server and send finished output to the browser, so they can read data directly and add no JavaScript to the page. Make a component a client component only when it needs state, effects or browser events, and keep that boundary as low in the tree as you can.

By CodingMarble · Published · 4 min read

A silver iMac on a desk in a bright room
Photo: Lee Campbell on Unsplash

The core idea

Traditional React ships a component's code to the browser, runs it there and builds the page from the result. Server Components change where some of that work happens. A server component runs only on the server, either at build time or per request, and what reaches the browser is its rendered output rather than its code. Because that code never downloads, a server component adds nothing to your JavaScript bundle, however many libraries it uses.

This is not the same as server-side rendering of older frameworks. With plain server-side rendering, every component still ships its code so the page can become interactive. With Server Components, a component that only displays data can stay entirely on the server. In frameworks such as Next.js with the App Router, components are server components by default, and you opt in to client behaviour explicitly.

What runs where

A server component can be asynchronous, can read a database or call an internal service directly, and can use secrets such as API keys because none of its code is delivered. It cannot hold state with useState, cannot use effects, and cannot respond to clicks or typing, since there is no live component in the browser to receive the event.

A client component is the familiar kind. It is marked with a directive, ships its code to the browser, and can use state, effects, refs and event handlers. It is still pre-rendered to HTML on the server for the first load, then hydrated in the browser. So the distinction is not whether code runs on the server at all, but whether its code is also sent to, and run in, the browser.

To see this in your own project, open the browser's network panel and look at the JavaScript requests when a page loads. Moving a display-only component from client to server should reduce the amount of script delivered, and you can confirm that rather than trusting the theory.

Data fetching without extra layers

The biggest practical gain is that a server component can fetch data where it uses it. There is no need for a separate endpoint, a loading state in the browser and an effect to call it. The component awaits the data and renders. This removes a round trip, because the server is usually close to the database, and it keeps credentials out of the browser entirely.

TSX· A server component reading data directly. The fetchProducts function is a placeholder for your own data access.
// app/products/page.tsx  (server component by default)
import { fetchProducts } from "@/lib/products";
import { AddToCart } from "./AddToCart";

export default async function ProductsPage() {
  const products = await fetchProducts(); // runs on the server

  return (
    <ul>
      {products.map((p) => (
        <li key={p.id}>
          <h2>{p.name}</h2>
          <p>{p.summary}</p>
          <AddToCart productId={p.id} />
        </li>
      ))}
    </ul>
  );
}

Notice that the page itself has no interactivity, so it stays on the server, and only the button, which must respond to clicks, is a separate client component. Independent data requests in different components can run in parallel, but sequential awaits inside one component run one after another, so when two requests do not depend on each other, start them together with Promise.all.

The use client boundary

The directive 'use client' at the top of a file marks a boundary. That file, and everything it imports, becomes part of the client bundle. Components below the boundary are client components even if they do not carry the directive themselves. This is why placement matters: putting the directive on a large layout pulls everything beneath it into the browser.

TSX· A small client component. Only this file and its imports are sent to the browser.
// app/products/AddToCart.tsx
"use client";

import { useState } from "react";

export function AddToCart({ productId }: { productId: string }) {
  const [added, setAdded] = useState(false);

  return (
    <button
      type="button"
      onClick={() => setAdded(true)}
      aria-pressed={added}
    >
      {added ? "Added" : "Add to cart"}
    </button>
  );
}

A client component can render server components if they are passed in as children or props, because the server has already produced their output. It cannot import a server component directly, since that would drag server-only code across the boundary. Props passed from server to client must be serialisable: strings, numbers, plain objects and arrays work, while functions and class instances do not.

Common mistakes

  • Adding the client directive to every file to silence an error. This removes the benefit and often hides the real problem, which is a hook used in the wrong place.
  • Marking a whole page or layout as a client component because one small part needs state. Extract that part into its own file instead.
  • Leaking secrets by importing server-only code into a client file. Use a server-only guard package or keep such code in modules that clearly cannot be imported by client components.
  • Passing functions or database objects as props across the boundary, which fails because they cannot be serialised.
  • Fetching data in a client effect out of habit, when a server component could have loaded it before the page was sent.
  • Using browser APIs such as window or localStorage in a server component, where they do not exist.

When an error says a hook cannot be used in a server component, the fix is almost never to convert the whole tree. Find the smallest piece that needs the hook and move that piece into a client file.

When to choose each

Use a server component for anything that mostly displays content: page shells, article bodies, product listings, dashboards that read data, and anything that touches a database or a secret. Use a client component for anything that responds to the user: forms with live validation, menus, modals, carousels, drag and drop, charts that react to input, and anything using browser-only APIs.

A reliable pattern is to keep the outer structure on the server and push interactive pieces to the leaves. Start every new component as a server component and add the directive only when the compiler or your own requirement forces it. This default produces smaller bundles and simpler data flow without extra effort.

Server Components are not the right fit when your whole app is a highly interactive tool, such as a drawing editor or a spreadsheet, where almost everything is state and events. There, a mostly client-side design is natural and the server components serve only as a thin shell. Check your framework's current documentation for supported features and caching behaviour, since these details change between releases.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.