How do Server Components and Client Components work together in the same app?
Short answer
Server Components can render Client Components as children, letting a mostly static page include small interactive pieces exactly where needed.
Advertisement
AModel answer
Server Components can render Client Components as children, letting a mostly static page include small interactive pieces exactly where needed. However, a Server Component cannot be directly imported and rendered inside a Client Component, since Client Components have already been sent to the browser and cannot run server only code.
// Server Component
function ProductPage({ productId }) {
const product = await getProduct(productId); // server only data fetching
return (
<div>
<h1>{product.name}</h1>
<AddToCartButton productId={productId} /> {/* a Client Component */}
</div>
);
}Real-world example
A product page fetches its data directly on the server for speed, but includes a small interactive AddToCartButton Client Component right where a customer needs to click, combining the strengths of both approaches on one page.
Likely follow-ups
- How would you pass data from a Server Component down into a Client Component as a prop?
- Why can a Client Component not directly import and render a Server Component?
Related topics