Menu

Layouts and Templates

Lesson 2: Layouts and Templates

What is a layout?

A layout is UI shared by several pages, such as a header, footer, or sidebar. It wraps every page in its folder and in all nested folders.

  • Layouts stay mounted during navigation, so their state is kept and they do not re-render.
  • Layouts nest: a layout in app/courses/ sits inside the root layout.
  • A layout receives the page (or nested layout) as children.

Example

// app/courses/layout.tsx
import Link from 'next/link';

export default function CoursesLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <div className="flex gap-8">
      <aside>
        <h2>Categories</h2>
        <nav>
          <Link href="/courses/data">Data</Link>
          <Link href="/courses/web">Web Development</Link>
          <Link href="/courses/design">Design</Link>
        </nav>
      </aside>
      <section>{children}</section>
    </div>
  );
}

The resulting tree for /courses/data:

RootLayout (app/layout.tsx)       ← <html>, <body>, site header
└─ CoursesLayout (app/courses/layout.tsx) ← category sidebar
   └─ DataPage (app/courses/data/page.tsx)

How it works

  • When the user moves from /courses/data to /courses/web, only the page changes. The sidebar stays in place.
  • Since Next.js 16, shared layouts are downloaded once when several links point to pages that use them, which reduces prefetch traffic.
  • Layouts do not receive searchParams, because they are not re-rendered on every navigation.

Layout versus template

Feature layout.tsx template.tsx
Re-mounts on navigation No Yes
Keeps component state Yes No (resets)
Runs effects again No Yes
Typical use Headers, sidebars, shells Enter animations, per-page logging, resetting forms

Use a layout by default. Use a template only when you need a fresh instance on each navigation.

Common mistakes

Mistake Effect Fix
Fetching user-specific data in the root layout Every page becomes dynamic Fetch it in a smaller component wrapped in Suspense (Module 3)
Forgetting {children} Pages under the layout never appear Always render children
Expecting a layout to re-run on navigation Stale data such as an active tab Use usePathname() in a Client Component

Key takeaways

  • Layouts wrap pages, nest by folder, and persist across navigation.
  • Use templates only when UI must reset on every navigation.

Try it: Add a site header and footer to the root layout, and a category sidebar to app/courses/layout.tsx.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details