What Is Layout in Next.js: Explanation and Example
Next.js, a layout is a special component that wraps pages to provide a consistent structure like headers, footers, or navigation across multiple pages. It helps avoid repeating code by sharing common UI elements and is defined using the app/layout.js file in the App Router.How It Works
Think of a layout in Next.js like the frame of a picture. Just as a frame holds and shows different pictures in the same style, a layout wraps around different pages to keep a consistent look and feel. Instead of adding the same header or footer to every page, you create a layout once and it automatically appears on all pages inside it.
In Next.js, layouts are special components placed in the app/layout.js file or inside folders in the app directory. When you visit a page, Next.js loads the layout first, then the page content inside it. This makes your app organized and faster because shared parts don’t reload every time you switch pages.
Example
This example shows a simple layout with a header and footer that wraps around the page content.
export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header style={{ padding: '1rem', backgroundColor: '#eee' }}> <h1>My Website</h1> </header> <main>{children}</main> <footer style={{ padding: '1rem', backgroundColor: '#eee', marginTop: '2rem' }}> <p>© 2024 My Website</p> </footer> </body> </html> ) } // Example page inside app/page.js export default function HomePage() { return <p>Welcome to the homepage!</p> }
When to Use
Use layouts in Next.js whenever you want to keep parts of your website consistent across many pages. For example, if your site has the same navigation menu, header, or footer on every page, a layout saves you from copying that code everywhere.
Layouts are also useful for adding global styles, setting up fonts, or wrapping pages with providers like authentication or theme contexts. They make your app easier to maintain and improve user experience by avoiding flickers when switching pages.
Key Points
- Layouts wrap pages to share common UI like headers and footers.
- Defined in
app/layout.jsor nested folders in the App Router. - Improve performance by keeping shared parts persistent across page changes.
- Help organize code and reduce repetition.
Key Takeaways
app/layout.js file in the App Router.