Layouts
Every Trailhead page shows the same header, and every page under /trails also shows a filter sidebar. Copying those into each page would be tedious, and worse, they would be rebuilt on every click, losing whatever filter the hiker had picked. A layout draws them once and keeps them.
The rule
A layout wraps its whole subtree and stays put while the page inside changes.
A layout.tsx file default-exports a component that receives children and renders it where the page should go.
The root layout at app/layout.tsx is required. It wraps every page and must render the <html> and <body> tags:
// app/layout.tsx
import Link from "next/link";
import "./globals.css";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<header>
<Link href="/">Trailhead</Link> <Link href="/trails">Trails</Link>
</header>
{children}
</body>
</html>
);
}A layout deeper in the tree wraps only its subtree, nested inside the layouts above it:
// app/trails/layout.tsx
import { FilterSidebar } from "./filter-sidebar";
export default function TrailsLayout({ children }: { children: React.ReactNode }) {
return (
<div className="two-columns">
<FilterSidebar />
<main>{children}</main>
</div>
);
}For /trails/misty-ridge React builds: RootLayout → TrailsLayout → the trail page.
Key behaviour: when the hiker moves from one trail to another, only the page changes. Both layouts stay mounted and are not re-rendered, so any state inside them, like the sidebar's selected filter, survives. Layouts are server components by default, can fetch data, and receive the route's params. They do not receive searchParams, because they are not re-rendered when the query string changes.
The shortcut
To see what wraps a page, walk its path from the root and collect every layout.tsx on the way. They nest in that order, outermost first.
Root
app/layout.tsx: html, body and the header.
The trap is expecting a layout to re-run on each navigation, for example to reset a form or log a page view. It will not. That is the job of a template, the next lesson.
Drills
Answer fast — trust the rule.
Which file must render the <html> and <body> tags?
Where does a layout put the current page?
A hiker picks "Easy" in the trails sidebar, then clicks another trail. What happens to the choice?
Which layouts wrap /about, given app/layout.tsx and app/trails/layout.tsx?
Remember
- A layout wraps its whole subtree via
childrenand stays mounted while the page changes. - Shortcut: walk the path from the root and collect every layout, outermost first.
- Trap: layouts do not re-run on navigation and do not receive
searchParams.
