Next.jsMedium

What is a Shared Component?

A shared component is one that can run as either a Server or Client Component because it only renders props: no hooks, no browser APIs and no server-only APIs. It becomes a Server Component when imported from server code and a Client Component when imported from a "use client" module.

Characteristics

  • Pure rendering from props: buttons, cards, badges, layout primitives, formatters.
  • No useState/useEffect, no window, no cookies() or database access.
  • Not async (an async component could only be a Server Component).
  • No directive at the top of the file.

Why it is useful

  • Reuse the same component in server-rendered pages and interactive client widgets.
  • When used from the server, it adds nothing to the client bundle.
  • When used from a client tree, it is bundled once for that client code.

How the environment is decided

The importer decides. A shared Badge imported by app/page.tsx renders on the server. The same Badge imported by app/cart-drawer.tsx (which starts with "use client") is bundled for the browser.

Utilities follow the same idea

Formatting helpers, validation schemas (Zod) and constants can be imported on both sides. Mark modules that must never reach the browser with import "server-only".

Pitfall

Adding a hook later silently breaks server usages. Lint rules or tests that import shared components in a server context catch this early.

Code example

tsx
1// components/price.tsx - shared: no directive, no hooks, no server APIs
2type Props = { amount: number; currency?: string };
3
4export function Price({ amount, currency = "USD" }: Props) {
5 const text = new Intl.NumberFormat("en-US", { style: "currency", currency }).format(amount);
6 return <span className="font-semibold tabular-nums">{text}</span>;
7}
8
9// app/products/page.tsx - Server Component uses it (zero client JS)
10// import { Price } from "@/components/price";
11// <Price amount={product.price} />
12
13// app/cart/cart-drawer.tsx - Client Component uses the same component
14// "use client";
15// import { useState } from "react";
16// import { Price } from "@/components/price"; // bundled for the browser here
17// export function CartDrawer({ total }: { total: number }) {
18// const [open, setOpen] = useState(false);
19// return <button onClick={() => setOpen(!open)}>Cart <Price amount={total} /></button>;
20// }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app