Next.jsMedium
How do you create nested layouts in the App Router?
Add a layout.tsx to any route folder. It wraps every page and layout below it, and layouts nest automatically: app/layout.tsx wraps app/dashboard/layout.tsx, which wraps app/dashboard/settings/page.tsx.
How nesting works
For /dashboard/settings, Next.js renders:
RootLayout > DashboardLayout > SettingsLayout (if any) > Page
Each layout receives children (the next level down), plus any parallel route slots and a params promise.
Why nested layouts matter
- Persistence: on navigation between sibling routes, the shared layout stays mounted. Its state, scroll position and any open dropdowns survive, and it is not re-rendered on the server.
- Partial rendering: only the segments that changed are fetched and rendered.
- Colocated boundaries: add
loading.tsxanderror.tsxper level for granular streaming and error isolation.
Rules
- The root layout is required and must render
<html>and<body>. - Layouts can be async Server Components that fetch data. With Cache Components, cache that data with
"use cache"or put request-time parts in<Suspense>, otherwise the layout blocks the static shell. - Layouts do not receive
searchParamsand do not re-render on query changes. Use a Client Component withuseSearchParamsif a layout must react to the query. - Data fetched in a layout and its page is not shared via props. Fetch it in both places;
fetchmemoization orReact.cachededuplicates the request. - Use
template.tsxinstead when you want a fresh instance on every navigation.
Code example
tsx
1// app/layout.tsx - root layout (required)2export default function RootLayout({ children }: { children: React.ReactNode }) {3 return (4 <html lang="en">5 <body>6 <header>Acme</header>7 {children}8 </body>9 </html>10 );11}1213// app/dashboard/layout.tsx - wraps every /dashboard/* page14import { Suspense } from "react";15import { UserMenu } from "./user-menu"; // reads cookies, so it streams1617export default function DashboardLayout({ children }: LayoutProps<"/dashboard">) {18 return (19 <div className="flex">20 <nav className="w-56">21 <a href="/dashboard">Overview</a>22 <a href="/dashboard/settings">Settings</a>23 <Suspense fallback={<span>…</span>}>24 <UserMenu />25 </Suspense>26 </nav>27 <main className="flex-1">{children}</main>28 </div>29 );30}3132// app/dashboard/settings/page.tsx33// export default function Settings() { return <h1>Settings</h1>; }
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.