Next.js The Leaf Pattern
A leaf is a small component at the edge of the page. Keep client code in the leaves, and the page stays on the server.
The search box leaf
The box holds the typed text in state. On submit it moves the page to the search address.
'use client';
import { useRouter } from "next/navigation";
import { useState } from "react";
export default function SearchBox() {
const [value, setValue] = useState("");
const router = useRouter();
return (
<form
onSubmit={(event) => {
event.preventDefault();
router.push(`/?q=${encodeURIComponent(value)}`);
}}
>
<input
value={value}
onChange={(event) => setValue(event.target.value)}
placeholder="Search books"
/>
<button type="submit">Search</button>
</form>
);
}The server page around it
The home page is a Server Component. It reads the books and lists them. The search word in the address is read in a later lesson.
import SearchBox from "@/components/SearchBox";
export default async function Home() {
const books = searchBooks("");
return (
<main>
<h1>My Bookshelf</h1>
<SearchBox />
<p>{books.length} books on the shelf</p>
<ul>{/* the book list */}</ul>
</main>
);
}Example
curl -s http://localhost:3111/ | grep -o 'placeholder="Search books"'Key points
- Leaf: a small component at the edge of a page, with no children of its own
- The search box is a leaf. It holds the typed text and sends the search.
- The page around it stays a Server Component. It reads the books and lists them.
- A client leaf gets only the props it needs. Here it gets nothing at all.
- One leaf per job keeps the client code small. Each leaf does one thing.
- useRouter: the hook that moves the page in the browser. router.push sends the reader to the search address.
In this example, the check reads the home page and finds the search box placeholder. The box is there, inside a server page. The page lists the books, and the box is the one client leaf on it. Typing in the box is a browser job, so curl shows the box but cannot show the typing. The search itself is checked in the lesson on search params, where the address carries the query.
Note
A big client page ships big client code. Small leaves keep the page light.
Try it Yourself
Edit the code, then press Run.
Running is simulated · TypeScript Playground
Exercise
What is a client leaf?