Next.js Curriculum
EasyFile-System Conventions100% Free25 min read

The Route Hierarchy: Layouts, Templates, and Pages

The 30-Second Interview Answer

Layouts (layout.tsx) wrap page hierarchies, preserve client state across navigations, and do not re-render their DOM on route changes. Templates (template.tsx) create a new instance on every navigation, resetting state and DOM, which is essential for page enter animations and reset-on-navigation behaviors.

Learning Objectives

Understand the component hierarchy: layout wraps template, which wraps error, loading, and page.

Explain state preservation in layout.tsx during client-side navigation.

Identify when to use template.tsx instead of layout.tsx (animations, logging, form resets).

Structure nested layouts for multi-level dashboard applications.

Prerequisites & Background Knowledge
React component compositionDOM persistenceApp Router routing

Why Interviewers Care

Core architecture question asked in technical screens to distinguish surface-level users from deep practitioners.

The Challenge

Explain the structural and lifecycle differences between layout.tsx and template.tsx in Next.js App Router. When should an engineer deliberately choose a template over a layout?

Code Architecture & Implementation

1// app/dashboard/layout.tsx
2// Persistent layout: Persistent sidebar state & audio playback across navigation
3'use client';
4import { useState } from 'react';
5import Link from 'next/link';
6
7export default function DashboardLayout({ children }: { children: React.ReactNode }) {
8 const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
9
10 return (
11 <div className="dashboard-grid">
12 <aside className={sidebarCollapsed ? 'collapsed' : 'expanded'}>
13 <button onClick={() => setSidebarCollapsed(!sidebarCollapsed)}>Toggle</button>
14 <nav>
15 <Link href="/dashboard/analytics">Analytics</Link>
16 <Link href="/dashboard/settings">Settings</Link>
17 </nav>
18 </aside>
19 {/* State in this layout is PRESERVED when switching between Analytics & Settings! */}
20 <main>{children}</main>
21 </div>
22 );
23}
24
25// app/dashboard/template.tsx
26// Template: Remounts on EVERY navigation. Creates fresh DOM & resets state.
27'use client';
28import { useEffect } from 'react';
29
30export default function DashboardTemplate({ children }: { children: React.ReactNode }) {
31 useEffect(() => {
32 // Runs on EVERY page transition inside /dashboard/*
33 console.log('Page view tracked on navigation');
34 }, []);
35
36 return <div className="page-transition-fade-in">{children}</div>;
37}

Architectural Explanation

The App Router Segment Component Hierarchy

For any folder segment, Next.js composes the component tree in the following strict order:

jsx
<Layout>
  <Template>
    <ErrorBoundary fallback={<Error />}>
      <Suspense fallback={<Loading />}>
        <Page />
      </Suspense>
    </ErrorBoundary>
  </Template>
</Layout>

Layout (layout.tsx)

  • Persistence: Layouts do not unmount or remount when navigating between sibling routes (e.g. from /dashboard/analytics to /dashboard/settings).
  • State Preservation: Any React state (useState), video playback, or scroll position inside a layout remains completely uninterrupted.
  • Performance: Minimizes re-rendering work during client transitions.

Template (template.tsx)

  • Re-instantiation: Next.js creates a brand new instance of a template on every navigation.
  • State Reset: State inside the template is reset to initial values.
  • Use Cases:
    1. CSS enter/exit animations that must trigger on every page transition.
    2. Features relying on useEffect firing on navigation (e.g., page view telemetry).
    3. Resetting user inputs (e.g., feedback modal forms that must wipe on navigation).

Common Mistakes & Anti-Patterns

Using template.tsx for complex navigation sidebars, causing unneeded re-rendering and jarring UI flashes on every route change.

Putting `<html>` and `<body>` tags in nested layouts (only the root layout may define them).

Expecting a layout to re-run its useEffect hooks on child route transitions.

Interview Follow-Up Traps

Interviewer asks: "Can you pass state or props from layout.tsx down to page.tsx?" Trap answer: Yes, via props. Correct answer: No! Next.js layouts only receive { children: React.ReactNode } and route params. To share state between a layout and page, you must use React Context, URL search params, or a client state store (Zustand).

Interviewer asks: "Does layout.tsx re-render on the server when a user navigates between child pages?" Trap answer: Yes, it fetches fresh data. Correct answer: During client navigation, Next.js only fetches the RSC payload for the changed leaf page segment, reusing the existing layout tree.

Frequently Asked Questions

Can you have multiple layouts in a single application?

Yes. Layouts nest hierarchically: the root layout wraps child layouts, which wrap sub-layouts down to the leaf page.

Yes. Layouts can be async Server Components that query databases or APIs directly.

The root layout (app/layout.tsx) is required in every App Router application and must define the <html> and <body> tags.

Use template.tsx with Framer Motion or CSS animation classes, as templates remount on every navigation.

Yes. If both are defined, Next.js renders the layout as the parent wrapping the template.