Sub topic 9
Composing Server and Client Components
This chapter assumes you know React components, props, JSX, useState, and async/await. It also assumes you have met the "use client" boundary and the idea that props must be serializable to cross it. Here you will learn the patterns that let Server and Client Components work together in one tree, and the mistakes that break them.
The rule that drives every pattern
A Server Component can import and render a Client Component. A Client Component cannot import a Server Component.
The reason is where code runs. When a module has "use client", it and everything it imports become part of the client bundle. If that module imported a Server Component, the server-only code would have to ship to the browser. That code may use a database driver, read secrets, or await data, and none of that can run in the browser.
This does not mean a Server Component can never appear inside a Client Component's output. It can, as long as the Server Component is created by a Server Component higher in the tree and handed down as a prop. That is the central technique of this chapter.
Pattern 1: Server parent, Client child
This is the most common shape. The server fetches data and passes the result as props to a Client Component that needs state or event handlers.
// app/page.js (Server Component)
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>
);
}// 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>
);
}The list is rendered on the server and arrives in the payload as plain elements. Only Counter has code that runs in the browser. The prop initial is a number, so it serializes without trouble.
Pattern 2: Server Components as `children`
A Client Component often needs to wrap content, such as a modal, tab panel, or accordion. You want the wrapper's state on the client, but the content may be a Server Component.
// app/Modal.js
'use client';
import { useState } from 'react';
export default function Modal({ children }) {
const [open, setOpen] = useState(false);
return (
<>
<button onClick={() => setOpen(!open)}>Toggle</button>
{open && <div className="modal">{children}</div>}
</>
);
}
// app/page.js (Server Component)
import Modal from './Modal';
import Comments from './Comments'; // a Server Component
export default function Page() {
return (
<Modal>
<Comments />
</Modal>
);
}Page is the component that creates the <Comments /> element, so Page is the one that renders it. The server runs Comments, and the result goes into the payload as already-rendered output. Modal receives that output as children and decides only where to place it.
Two consequences follow:
Commentsnever needs to be in the client bundle, so its dependencies stay on the server.Modalre-rendering whenopenchanges does not re-runComments. The children are the same output the server already produced.
Pattern 3: Server Components as other props
children is only the most common slot. Any prop can carry rendered output, which lets a Client Component expose several slots.
// app/Tabs.js
'use client';
import { useState } from 'react';
export default function Tabs({ overview, details }) {
const [tab, setTab] = useState('overview');
return (
<div>
<button onClick={() => setTab('overview')}>Overview</button>
<button onClick={() => setTab('details')}>Details</button>
{tab === 'overview' ? overview : details}
</div>
);
}
// app/page.js (Server Component)
import Tabs from './Tabs';
import Overview from './Overview'; // Server Component
import Details from './Details'; // Server Component
export default function Page() {
return <Tabs overview={<Overview />} details={<Details />} />;
}Both Overview and Details run on the server on every render of Page, even though only one is visible. If one is expensive, wrap it in Suspense (covered in the streaming chapter) so it does not block the rest.
Pattern 4: Push the boundary down
The "use client" directive affects the whole import subtree of a module. If you mark a large layout as a Client Component, every component it imports becomes client code.
Compare these two designs for a page with a static article and a "like" button:
| Design | Where `"use client"` goes | Result |
|---|---|---|
| Boundary high | On the whole `Article` component | Article text, markdown parser, and button all ship to the browser |
| Boundary low | On a small `LikeButton` only | Only the button's code ships. The article stays on the server |
Extract the interactive part into its own small component and keep the rest on the server. Ask of each component: does it need state, effects, browser APIs, or event handlers? If not, leave it as a Server Component.
Pattern 5: Shared components
A module with no directive and no server-only or client-only features is neutral. Its environment depends on who imports it:
- Imported from a Server Component, it runs on the server.
- Imported from a Client Component, it becomes part of the client bundle and runs there (and also during SSR).
A formatting helper or a presentational component such as a Badge is a good candidate. Do not use hooks like useState in such a module, because that breaks it when a Server Component imports it.
Common errors
Importing a Server Component into a Client Component
// app/Sidebar.js
'use client';
import Comments from './Comments'; // Server Component with a database call
export default function Sidebar() {
return <Comments />;
}Because Sidebar is a client module, Comments is pulled into the client bundle and treated as client code. If it uses server-only APIs, the build fails or it breaks at runtime. If it only looks like ordinary code, it silently becomes a Client Component and loses its server benefits. Fix it by passing <Comments /> in as children or a prop from a Server Component.
Passing a non-serializable prop
A Server Component cannot pass a plain function, class instance, or similar value to a Client Component, because the payload can only carry serializable data.
// app/page.js (Server Component)
import Button from './Button'; // Client Component
export default function Page() {
// Wrong: a plain function cannot cross the boundary
return <Button onClick={() => console.log('hi')} />;
}Move the handler into the Client Component, or pass the data it needs. A Server Function (marked with "use server") is the exception, because it crosses as a reference.
Using hooks in a Server Component
useState, useEffect, and event handlers such as onClick are not available in Server Components. The fix is to move that part into a small Client Component, as in Pattern 1.
Context providers
createContext and useContext need client code. A provider is therefore a Client Component that accepts children:
// app/ThemeProvider.js
'use client';
import { createContext, useState } from 'react';
export const ThemeContext = createContext('light');
export default function ThemeProvider({ children }) {
const [theme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
{children}
</ThemeContext.Provider>
);
}Mount it near the root from a Server Component layout. Because the rest of the tree arrives as children, Server Components beneath the provider stay on the server.
What the payload shows
The payload makes the composition visible. Here is a simplified, illustrative payload for the first example. The exact syntax differs between React versions and frameworks.
1:I["app/Counter.js",["chunk-counter.js"],"default"]
0:["$","main",null,{"children":[["$","h1",null,{"children":"Posts"}],["$","ul",null,{"children":[["$","li",null,{"children":"First post"}]]}],["$","$L1",null,{"initial":1}]]}]Server-rendered parts (main, h1, ul, li) appear as finished elements. Counter appears as $L1, a pointer to the client module declared in row 1, with its serializable props. In the Modal example, the Comments output would appear as finished elements inside the children prop of the Modal's reference. No Comments code is referenced at all.
Decision checklist
- Does the component need state, effects, refs to the DOM, browser APIs, or event handlers? If yes, make it a Client Component.
- Is it only displaying data, or does it fetch or read server resources? Keep it a Server Component.
- Does a Client Component need to display server-rendered content? Pass it as
childrenor another prop. - Are you marking a big module
"use client"? Look for a smaller piece that can be extracted. - Are props crossing the boundary all serializable? If not, restructure.
Exercise
A Client Component named Accordion holds openIndex in state. You want each panel's body to be a Server Component that queries a database. Your colleague proposes importing the body components directly inside Accordion.js. What goes wrong, and how do you fix it?
Show answer
Importing them in Accordion.js pulls the body components into the client bundle, because everything a "use client" module imports becomes client code. The database code would fail or ship to the browser. Instead, have a Server Component (for example the page) create the body elements and pass them to Accordion as children or as props such as panels. The server renders them, and Accordion only chooses which one to show based on openIndex.
Exercise
A Server Component passes onSelect={(id) => setSelected(id)} to a Client Component List. Why does this fail, and what are two ways to fix it?
Show answer
A plain function is not serializable, so it cannot be placed in the payload. Fix 1: define the handler inside List (which owns the state) and have List call it. Fix 2: if the action must run on the server, pass a Server Function defined in a "use server" module, which crosses the boundary as a reference.