Skip to content
Watch the complete Next.js 15 course on YouTube

Layouts

Layouts in Next.js provide shared UI components that persist across multiple pages in your application. A layout typically includes elements like navigation bars, headers, or footers that maintain consistency throughout the user experience.

Creating a layout

To create a layout, export a React component from a layout.js or layout.tsx file. The component must accept a children prop, which Next.js uses to render the page content.

Root layout

Next.js requires a root layout file (layout.tsx) in the app directory. This file serves as the base layout for all pages in your application and is created automatically when you create a new Next.js project using the create-next-app command.

  • Directoryapp/
    • layout.tsx Root layout
    • page.tsx Home page

Here’s the basic structure of a root layout component:

export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}

The children prop represents the content from your page components. For example, when rendering the home page, the component in app/page.tsx becomes the children of this layout.

Adding shared UI elements

You can enhance the root layout by adding persistent UI elements. Here’s an example that includes a header and footer:

app/layout.tsx
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<>
<header style={{ backgroundColor: "lightblue", padding: "1rem" }}>
<p>Header</p>
</header>
{children}
<footer style={{ backgroundColor: "ghostwhite", padding: "1rem" }}>
<p>Footer</p>
</footer>
</>
);
}

The header and footer are shared across all pages in the application.

Benefits of layouts

Layouts allow you to share UI elements across multiple routes while preserving their state and avoiding re-renders. They’re essential for:

  • Navigation bars
  • Headers and footers
  • Persistent UI elements
  • Shared wrapper components