Thuta Learning
Next.js
BasicWeb DevelopmentIntermediate

Pages and Shared Layouts

Next.jsLesson 525 min

What you'll walk away with

  • Create a new route with page.tsx
  • Explain the root layout's job and why it needs html and body tags
  • Write a nested layout for a section and draw the component tree for a URL
  • Predict what happens to a layout's state during navigation

Explain it simply

Explain it simply

Copying the same header into every page means that changing it later requires editing many files, and one is easily missed. A layout keeps that repeated UI in one place and slots the current page into the middle through the children prop.

Picture a photo frame: the frame (the layout) stays put and only the photo inside (the page) is swapped. Moving from /notes to /notes/42 keeps the frame and replaces only the page, so navigation is quick and any state inside the frame survives.

Problem → Why → Solution

The problem: a header copied into every page, and a missing html/body

In the first version of Myanmar Notes, all three pages render <header>Myanmar Notes</header> themselves. When the team decides to add a logo, three files need editing and the about page is forgotten. Then the root layout is written to return a single <div> without html and body tags, and Next.js reports an error.

app/layout.tsx + pages
// app/layout.tsx: missing <html> and <body>
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return <div>{children}</div>;
}

// app/page.tsx, app/notes/page.tsx, app/about/page.tsx all repeat this:
export default function NotesPage() {
  return (
    <>
      <header>Myanmar Notes</header>  {/* copy 2 of 3: easy to forget one */}
      <h1>All notes</h1>
    </>
  );
}

Why does this happen?

In the App Router, Next.js does not add the html and body tags for you; the root layout must be the outermost part of the document. And when the header is copied into every page, nothing owns that UI anymore. Move it into a layout and it is owned in one place, with every page getting it automatically.

Core concept: pages are leaves, layouts are wrappers

page.tsx makes a route segment a public URL and default-exports a React component. It is the leaf of the tree: one URL shows one page. layout.tsx also default-exports a component, but it accepts a children prop and wraps its folder and every route below it. Whatever sits one level down, another layout or a page, arrives as children. A folder without page.tsx can still hold a layout; it simply has no URL of its own, and its layout wraps the routes inside it.

app/layout.tsx is the root layout and it is required. The document's <html> and <body> are written here and nowhere else, along with the lang attribute. Head information such as <title> is not written as tags; it is set through the metadata API, covered in the metadata lesson. The root layout is the right home for the header, footer, fonts and global CSS that every page shares.

Add a layout.tsx inside a folder and you get a nested layout. When /notes/42 opens, Next.js puts the notes layout inside the root layout and the note page inside the notes layout, nesting them exactly like the folders.

The most important behaviour is that layouts do not re-render during navigation. Moving between two pages that share a layout, Next.js renders only the segment that changed and keeps the layout, so the state of a Client Component inside it, such as text typed into a search box, is not lost. For the same reason a layout does not receive searchParams or anything else tied to the current page; load route-specific data in the page.

text
Component tree for /notes/42
----------------------------
app/layout.tsx              RootLayout   <html><body><header>
  app/notes/layout.tsx      NotesLayout  <aside> stays mounted
    app/notes/[id]/page.tsx NotePage     swapped on navigation
Mental model: frames inside frames
  1. Root layout owns html and body
  2. Folder layouts wrap in order
  3. The page arrives as children
  4. Navigation swaps only the page

To show UI on many pages, put it in the layout of the lowest folder that contains all of those pages.

General pattern

tsx
// app/<segment>/layout.tsx
export default function SegmentLayout({ children }: { children: React.ReactNode }) {
  return <div>{/* shared UI */}{children}</div>;
}

// app/<segment>/page.tsx
export default function SegmentPage() {
  return <h1>{/* this URL's content */}</h1>;
}

A layout accepts children: React.ReactNode and places it inside the shared UI. A page needs no props for this and returns the URL's content. In the root layout (app/layout.tsx) the return value must be <html> and <body> instead of a <div>.

Example: a root layout, a notes layout and the notes page

This block holds three files; each comment is the file's path. The root layout shares the site header with every page, and the notes layout adds a sidebar only for pages under /notes. Before running it, predict how the three components nest when /notes opens.

Notice that React.ReactNode is used without an import. The TypeScript setup of a Next.js project makes the React type namespace available, and the create-next-app template itself uses this style; writing import type { ReactNode } from "react" works just as well.

app/layout.tsx + app/notes/layout.tsx + app/notes/page.tsx
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="my">
      <body>
        <header>Myanmar Notes</header>
        {children}
      </body>
    </html>
  );
}

// app/notes/layout.tsx
export default function NotesLayout({ children }: { children: React.ReactNode }) {
  return (
    <div className="notes-shell">
      <aside>Your notes</aside>
      <main>{children}</main>
    </div>
  );
}

// app/notes/page.tsx
export default function NotesPage() {
  return <h1>All notes</h1>;
}

Code breakdown

  1. Root layout<html lang="my">

    The root layout owns the document's <html> and <body>. lang="my" tells browsers and screen readers that the site is in Myanmar.

  2. Shared header<header>Myanmar Notes</header>

    The header is written once, here, and appears on every page. Adding a logo means editing only this line.

  3. children{children}

    For /notes, children is NotesLayout with NotesPage inside it; for / it is app/page.tsx. The layout does not know what will arrive, it only provides the slot.

  4. Nested layout<aside>Your notes</aside>

    Because it lives in app/notes/layout.tsx, the sidebar appears only on /notes and routes below it such as /notes/42. Moving between notes does not rebuild this aside.

  5. Pagereturn <h1>All notes</h1>;

    The page cares only about its own URL's content; it knows nothing about the header or the sidebar.

You should see
Opening /notes shows the "Myanmar Notes" header at the top, then the "Your notes" sidebar, with the "All notes" heading inside main. Opening / shares only the header; the sidebar does not appear there.

Layouts versus templates

A layout staying mounted during navigation is usually exactly what you want. When you need the opposite, such as restarting an animation or resetting form state on every page change, use template.tsx instead of layout.tsx. A template also wraps children, but it mounts fresh on every navigation.

FileAfter navigation
layout.tsxStays mounted, state kept
template.tsxMounted again, state reset
page.tsxSwapped when the URL changes

In real projects

Layouts in real projects

In dashboard apps, every page under /dashboard shares a sidebar and a user menu. Put them in app/dashboard/layout.tsx and the sidebar stays still while you move between pages, keeping its scroll position and any open menus. Music apps put the audio player in a layout so the song keeps playing while the page changes.

Marketing sites often use one layout for landing pages and another, with a sidebar, for the docs section. A later lesson covers route groups, which split layouts without changing URLs. Either way the rule is the same: put a layout in the lowest folder that covers every page sharing that UI, and no higher, so unrelated pages do not inherit it.

Common mistakes

Common mistakes

1. Leaving html and body out of the root layout

If the root layout returns a <div> or a fragment, Next.js reports that required tags are missing from it. app/layout.tsx must always return <html> with a <body> inside. Nested layouts, on the other hand, must not add html or body again.

2. Cramming one route's data into the layout

Loading the current note's title inside the notes layout goes wrong: the layout does not re-render during navigation, so an old title can linger when the note changes. Layouts do not receive searchParams either. Load data that varies per URL in the page.

3. Forgetting the default export in a page file

With only a named export such as export function NotesPage(), Next.js cannot find the page component and reports an error. Both page.tsx and layout.tsx need export default.

Best practices

Best practices

  • Keep the root layout thin: html and body, global CSS, fonts, and only the header and footer that truly appear on every page.
  • Put a section's UI, such as a sidebar or tabs, in that section's folder layout rather than in the root layout.
  • Keep layouts as Server Components and split out only the interactive pieces, like a search box or a dropdown, as Client Components.
  • Give page components clear names such as NotesPage or ProfilePage; they are easier to read in error stacks and React DevTools.

Mini challenge

Mini challenge: a layout for the settings section

Add two pages to Myanmar Notes: /settings and /settings/profile. Both share a "Settings" heading and a section navigation, which must not appear on / or /notes.

  • app/settings/layout.tsx accepts children and shows <h1>Settings</h1> plus a <nav> with two links
  • app/settings/page.tsx shows a "General" heading
  • app/settings/profile/page.tsx shows a "Profile" heading and one sentence
  • No html or body in this layout: the root layout already owns them
app/settings/...
// app/settings/layout.tsx
export default function SettingsLayout(/* TODO: children prop with its type */) {
  // TODO: <section> with <h1>Settings</h1>, a <nav> linking to
  // /settings and /settings/profile, then the children
}

// app/settings/page.tsx
// TODO: default-export a page with an <h2>General</h2>

// app/settings/profile/page.tsx
// TODO: default-export a page with an <h2>Profile</h2> and a <p>

Expected: /settings shows the Settings heading, the General and Profile links, then "General". On /settings/profile the heading and nav stay the same while "Profile" appears below them.

Show hint

Type the layout's props as { children: React.ReactNode }. The Link component comes in the next lesson, so plain <a href> is fine for now. The pages appear below the layout's <h1>, so use <h2> in them.

Show solution
app/settings/...
// app/settings/layout.tsx
export default function SettingsLayout({ children }: { children: React.ReactNode }) {
  return (
    <section>
      <h1>Settings</h1>
      <nav>
        <a href="/settings">General</a> | <a href="/settings/profile">Profile</a>
      </nav>
      {children}
    </section>
  );
}

// app/settings/page.tsx
export default function SettingsPage() {
  return <h2>General</h2>;
}

// app/settings/profile/page.tsx
export default function ProfilePage() {
  return (
    <>
      <h2>Profile</h2>
      <p>Your name appears on every note you share.</p>
    </>
  );
}

Quick quiz 1 / 3

There are app/layout.tsx, app/notes/layout.tsx and app/notes/[id]/page.tsx. How do they nest when /notes/42 opens?

Quick quiz 2 / 3

What happens if the root layout only does return <main>{children}</main>;?

Quick quiz 3 / 3

You type "react" into a Client Component search box inside the notes layout, then follow a Link from /notes to /notes/42. What happens to the text?

What to remember

  • page.tsx is the leaf that makes a route public; layout.tsx is shared UI that wraps children.
  • The root layout, app/layout.tsx, is required and owns <html> and <body>.
  • Layouts nest by folder and do not re-render during navigation, so they keep their state.
  • Load per-URL data in the page, and use template.tsx when you need a reset on navigation.

Next.js — Layouts and Pages — Next.js

Next.js — Layouts and Pages — Next.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Pages and Shared Layouts | Thuta Learning