Sub topic 2
Server Components and Client Components: what each can do
This chapter covers the two kinds of component in an RSC-enabled framework and the capabilities that separate them. It assumes you know React components, props and JSX, useState and useEffect, and async/await. It also assumes you know the difference between client-side and server-side rendering. Later chapters cover the "use client" boundary, the payload format and serialization in detail. Here the goal is a clear model of what each kind of component is allowed to do, and why.
Two kinds of component, one tree
In an app built on React Server Components (RSC), every component belongs to one of two groups:
- A Server Component runs only on the server. Its code is never sent to the browser. React runs it, takes the elements it returns, and sends the result to the client.
- A Client Component is the kind of component you already know. Its code is sent to the browser, and it can hold state, run effects and handle events.
Both kinds live in the same component tree. A Server Component can render a Client Component, and a Client Component can render other Client Components. The difference is where the code runs and which React features it can use.
In a framework that supports RSC, a component is a Server Component by default. A module becomes client code only when its first statement is the "use client" directive. The exact placement rules come in the next chapter. For now, treat the directive as the switch that turns a module into client code.
What Server Components can do
A Server Component runs in a server environment, so it can use things the browser cannot offer:
- Await data directly. The component function can be
async. There is nouseEffectplus loading state for the first render. - Reach server-only resources. It can query a database, read files, or call an internal service. API keys and connection strings used in the component stay on the server.
- Keep dependencies out of the browser bundle. If a Server Component imports a large Markdown parser or a date library, that library is never downloaded by the user. Only the rendered output travels.
- Render once per request. The server runs the function, produces elements, and is done. The result is not a live component on the client.
Here is a Server Component that fetches posts and renders a Client Component:
// app/page.js (Server Component by default in an RSC framework)
import Counter from './Counter';
async function getPosts() {
const res = await fetch('https://example.com/api/posts');
return res.json();
}
export default async function Page() {
const posts = await getPosts();
return (
<main>
<h1>Posts</h1>
<ul>
{posts.map((p) => (
<li key={p.id}>{p.title}</li>
))}
</ul>
<Counter initial={posts.length} />
</main>
);
}Page is an async function that awaits getPosts() before it returns JSX. That is allowed only because it is a Server Component. The fetch call runs on the server, and the browser never sees this function.
What Server Components cannot do
A Server Component has no lifetime on the client, so anything tied to a client lifetime is unavailable:
- No state hooks such as
useStateoruseReducer. - No effect hooks such as
useEffectoruseLayoutEffect. - No event handlers such as
onClickoronChange. A function cannot be attached to a DOM node that the server never hydrates. - No browser APIs such as
window,localStorageorIntersectionObserver. - No
useContextorcreateContext. A Server Component cannot read or create client-side context.
These limits follow from one fact. State, effects and handlers all need a component that stays alive in the browser and re-renders when something changes. A Server Component does neither.
What Client Components can do
The Counter component that Page renders is a Client Component:
// app/Counter.js
'use client';
import { useState } from 'react';
export default function Counter({ initial }) {
const [count, setCount] = useState(initial);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}A Client Component can:
- Hold state and re-render when it changes.
- Run effects after rendering.
- Attach event handlers to elements.
- Use browser APIs, inside effects and handlers.
- Use context, custom hooks built on state or effects, and third-party libraries that depend on these.
What Client Components cannot do
- Be
asyncfunctions. Client Components cannotawaitduring render. Fetch in a Server Component and pass the result down, or use a client data library. - Use server-only resources. Anything the component imports ends up in the browser bundle. A database client or a secret imported here is shipped to users, or the build fails.
- Import a Server Component and keep it a Server Component. Once a Client Component imports a module, that module is part of the client bundle. Server Components must instead arrive as
childrenor other props. The composition chapter covers this pattern.
Client Components are also not "browser-only". On a first page load, a framework usually runs them on the server too, to produce HTML. Chapter 11 explains how that differs from RSC. The name describes where the component's code is sent and where it stays interactive, not the only place it runs.
Side-by-side summary
| Capability | Server Component | Client Component |
|---|---|---|
| Code sent to the browser | No | Yes |
| `async` component function | Yes | No |
| Direct database or file access | Yes | No |
| `useState`, `useEffect` | No | Yes |
| Event handlers such as `onClick` | No | Yes |
| Browser APIs | No | Yes (in effects and handlers) |
| Context (`useContext`, `createContext`) | No | Yes |
| Re-renders on the client | No | Yes |
How the two kinds fit together
Think of the tree as a server-rendered shell with interactive islands. The server runs the Server Components from the top down. When it reaches a Client Component, it does not run it for the payload. It records a reference to it and the props it was given. The client later loads that component's code and renders it.
The browser receives the finished elements for h1 and ul, plus a pointer to Counter and its props. It never receives the code of Page or getPosts.
Choosing the right kind
Start with a Server Component and move to a Client Component only when you need something from the client list. These questions help:
- Does it need state, an effect or an event handler? Use a Client Component.
- Does it need a browser API? Use a Client Component.
- Does it read data or secrets, or import a heavy library only for display? Use a Server Component.
- Is it only displaying data? A Server Component is usually enough.
Keep the interactive part small. If a page needs one button with a click handler, make the button a Client Component and leave the surrounding page on the server. Putting "use client" on the whole page sends all of its code to the browser and removes the benefits listed above.
Common errors
The framework reports most of these at build time or on the first render.
- Hook in a Server Component. Calling
useStatein a component with no"use client"produces an error saying the hook only works in a Client Component. Fix it by adding the directive to that module, or by moving the stateful part into a smaller component that has it. - Event handler on a server element. Passing
onClick={() => ...}to an element inside a Server Component fails, because functions defined on the server cannot be sent to the client as handlers. Move the interactive element into a Client Component. asyncClient Component. Marking a component with"use client"and also making itasyncis not supported. Move the fetch to a Server Component parent and pass the data in as props.- Secret leaked into client code. A module that reads
process.env.DATABASE_URLand is imported from a Client Component ends up in the browser bundle. Keep such modules imported only by Server Components.
What carries over to the next chapters
- Server Components render once on the server and produce output, not live components.
- Client Components bring state, effects, handlers and browser APIs, and their code is shipped.
- Props flow from server to client, so what a Server Component passes must be something that can be sent over the network. The serialization chapter covers the exact rules.
- The
"use client"directive marks where client code begins. The next chapter examines how that boundary works.
Exercise
A product page needs to (1) read a product from a database, (2) show its description, and (3) include an "Add to cart" button that updates a cart counter in the page. Which parts should be Server Components and which should be Client Components, and why?
Show answer
The page itself and the description display should be Server Components. They read the database directly with an async function, use no state or handlers, and keep the database code and any display-only libraries out of the browser bundle. The "Add to cart" button and its counter should be a Client Component, because they need an event handler and state. The page fetches the product on the server and passes the values the button needs, such as the product id, as serializable props to the Client Component.
Exercise
A teammate adds 'use client' to app/page.js and makes the component async so it can still fetch posts. What goes wrong, and how would you fix it?
Show answer
Client Components cannot be async, so the component fails. Marking the whole page as client code also ships the page and everything it imports to the browser. The fix is to remove 'use client' from page.js so it stays a Server Component that awaits the posts. The interactive piece, such as a button with state, then moves into its own small module with 'use client' and receives data as props.