0
0
NextjsConceptBeginner · 3 min read

Root Layout in Next.js: What It Is and How It Works

In Next.js, the root layout is a special component that wraps all pages and components in your app, providing a shared structure like headers or footers. It lives in the app/layout.js or app/layout.tsx file and ensures consistent layout and styling across your entire site.
⚙️

How It Works

The root layout in Next.js acts like the frame of a picture that holds all the pages inside it. Imagine your website as a house, and the root layout is the foundation and walls that stay the same no matter which room (page) you enter. This means you can put things like navigation menus, footers, or global styles in the root layout, and they will appear on every page automatically.

Technically, the root layout is a React component placed in the app/layout.js or app/layout.tsx file. Next.js uses this file to wrap all page components, so you don’t have to repeat common UI elements on every page. This makes your code cleaner and your app faster because shared parts don’t reload when you switch pages.

💻

Example

This example shows a simple root layout with a header and footer that appear on every page.

javascript
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>
  )
}
Output
A webpage with a header saying 'My Website' at the top, the page content in the middle, and a footer with '© 2024 My Website' at the bottom.
🎯

When to Use

Use the root layout whenever you want to keep parts of your website consistent across all pages. This includes navigation bars, footers, global fonts, or background colors. It is especially helpful for large websites where repeating the same layout code on every page would be tedious and error-prone.

For example, an online store can use the root layout to show the shopping cart icon and main menu on every page. A blog can keep the site title and footer consistent without rewriting them in each post.

Key Points

  • The root layout wraps all pages and components in Next.js.
  • It lives in the app/layout.js or app/layout.tsx file.
  • Use it to add shared UI like headers, footers, and styles.
  • It improves code reuse and page load speed.

Key Takeaways

The root layout in Next.js provides a shared structure for all pages.
It is defined in the app/layout.js or app/layout.tsx file as a React component.
Use it to add common UI elements like headers and footers once.
It helps keep your app consistent and improves performance.
Ideal for any site needing repeated layout parts across pages.