Topic 26 of 47
Nested Layout Layouts
Overview
Layouts can be nested inside specific route folders to create specialized UI shells for a sub-section of your app. Nested layouts wrap the pages inside their directory and maintain state across page navigations.
Syntax
tsx
// app/dashboard/layout.tsx
// This layout only applies to /dashboard and its children
export default function DashboardLayout({
children, // Will be a page or another nested layout
}: {
children: React.ReactNode;
}) {
return (
<section className="flex">
<Sidebar />
<main className="flex-1">{children}</main>
</section>
);
}Common Pitfalls
- Layout components do not re-render or lose their state when navigating between their child routes. This makes them perfect for persistent sidebars or media players.
- If you need to access the current pathname inside a layout, you must make it a Client Component ('use client') and use 'usePathname()'.
Real-World Example
How Next.js composes the Root Layout and a Nested Layout:
example
tsx
// Hierarchy when a user visits /dashboard/settings
// 1. RootLayout (app/layout.tsx)
// 2. DashboardLayout (app/dashboard/layout.tsx)
// 3. SettingsPage (app/dashboard/settings/page.tsx)
<html lang="en">
<body>
{/* Root Layout UI */}
<Navbar />
{/* Dashboard Layout UI */}
<section className="flex">
<Sidebar />
{/* The specific page */}
<main className="flex-1">
<h1>Settings</h1>
</main>
</section>
</body>
</html>