Next.jsMedium

How do you share state between Server and Client Components?

Server and Client Components do not share memory, so "state" is shared through the URL, cookies, props, context seeded from the server, and Server Functions that change server data and refresh the UI. Choose the channel by who needs to read it and whether it must survive a reload.

Channels

  • URL (search params and path): the best place for shareable UI state such as filters, tabs and pagination. Server Components read searchParams; Client Components use useSearchParams and update with router.replace.
  • Cookies: state the server must know on every request (theme, locale, session, cart ID). Set them in Server Functions or Route Handlers with (await cookies()).set(); read them in Server Components.
  • Props: server to client, one direction, a snapshot at render time.
  • Context seeded from the server: fetch in a layout, pass to a client provider. Client components share and update it locally.
  • Server data + Server Functions: the client calls an action that writes to the database and calls updateTag or refresh(); the server re-renders with the new state in the same response.

Client-only state

State that only matters in the browser (open menus, form drafts) can live in useState, Zustand or Jotai. With Cache Components, pages stay mounted in a hidden <Activity> when you navigate away, so local state survives Back navigation.

Pitfalls

  • Do not put per-user data in module-level variables on the server; they are shared across all requests and users.
  • Changing client state does not re-run Server Components. Use the URL or a Server Function plus router.refresh().

Code example

tsx
1// app/products/page.tsx (server reads URL state)
2import { Filters } from "./filters";
3import { Suspense } from "react";
4
5async function List({ searchParams }: { searchParams: Promise<{ color?: string }> }) {
6 const { color } = await searchParams;
7 const items = await fetch(`https://api.example.com/items?color=${color ?? ""}`).then((r) => r.json());
8 return <p>{items.length} items</p>;
9}
10
11export default function Page(props: PageProps<"/products">) {
12 return (
13 <>
14 <Filters />
15 <Suspense fallback={<p>Loading…</p>}>
16 <List searchParams={props.searchParams as Promise<{ color?: string }>} />
17 </Suspense>
18 </>
19 );
20}
21
22// app/products/filters.tsx (client writes URL state)
23// "use client";
24// const router = useRouter(); const params = useSearchParams();
25// <select value={params.get("color") ?? ""} onChange={(e) => router.replace(`?color=${e.target.value}`)} />
26
27// app/actions.ts (cookie state)
28// "use server";
29// export async function setTheme(theme: "light" | "dark") {
30// (await cookies()).set("theme", theme, { path: "/", maxAge: 60 * 60 * 24 * 365 });
31// }

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