Layouts & Templates
Sharing UI across multiple pages in Next.js
🎨 What are Layouts & Templates?
Layouts and templates let you share UI components like headers, sidebars, and footers across multiple pages. Layouts preserve state between navigations, while templates create fresh instances for each route.
// app/layout.js - Wraps all pages
export default function RootLayout({ children }) {
return <html><body>{children}</body></html>
}
Layout vs Template
Both layouts and templates wrap page content, but they behave differently. Layouts maintain state and don't re-render on navigation, making them perfect for persistent UI. Templates re-render on each route change, useful for animations or resetting state.
Layouts
Preserve state between routes
// layout.js
export default function Layout({ children })
Templates
Re-render on navigation
// template.js
export default function Template({ children })
Nested Layouts
Stack layouts in folders
app/dashboard/layout.js
→ Wraps dashboard pages
Root Layout
Required top-level layout
app/layout.js
→ Wraps entire app
🔹 Root Layout (Required)
Every Next.js app needs a root layout with html and body tags:
// app/layout.js
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<h1>My Website</h1>
</header>
<main>{children}</main>
<footer>© 2025</footer>
</body>
</html>
)
}
Wraps all pages with header and footer
My Website
[Page content goes here]
© 2025
🔹 Nested Layouts
Create section-specific layouts for different parts of your app:
🔸 Dashboard Layout Example
// app/dashboard/layout.js
export default function DashboardLayout({ children }) {
return (
<div style={{ display: 'flex' }}>
<aside>
<nav>
<a href="/dashboard">Home</a>
<a href="/dashboard/settings">Settings</a>
</nav>
</aside>
<main>{children}</main>
</div>
)
}
🔹 Templates for Fresh State
Use templates when you need to reset state on navigation:
🔸 Animation Template
// app/template.js
'use client'
export default function Template({ children }) {
return (
<div className="fade-in">
{children}
</div>
)
}
// This re-renders on every route change
// Perfect for page transitions!
When to use Templates:
- Page transition animations
- Resetting form state
- Analytics tracking on route change
- Features that need fresh instances
🔹 Layout Composition
Layouts nest automatically based on folder structure:
Folder Structure:
app/
layout.js (Root - wraps everything)
page.js → /
blog/
layout.js (Blog - wraps blog pages)
page.js → /blog
[slug]/
page.js → /blog/post-1
// app/blog/layout.js
export default function BlogLayout({ children }) {
return (
<div>
<h2>Blog Section</h2>
{children}
</div>
)
}
// Renders inside RootLayout automatically!
🔹 Metadata in Layouts
Add metadata to layouts for SEO and social sharing:
// app/layout.js
export const metadata = {
title: 'My Website',
description: 'Welcome to my site',
}
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}