- Next.js
- App Router File Conventions
- The Route Hierarchy: Layouts, Templates, and Pages
Next.js Layout vs Template: App Router Hierarchy Explained
In Next.js, 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
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.tsx2// Persistent layout: Persistent sidebar state & audio playback across navigation3'use client';4import { useState } from 'react';5import Link from 'next/link';67export default function DashboardLayout({ children }: { children: React.ReactNode }) {8 const [sidebarCollapsed, setSidebarCollapsed] = useState(false);910 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}2425// app/dashboard/template.tsx26// Template: Remounts on EVERY navigation. Creates fresh DOM & resets state.27'use client';28import { useEffect } from 'react';2930export 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 }, []);3536 return <div className="page-transition-fade-in">{children}</div>;37}
Next.js Layout vs Template Explained
The App Router Segment Component Hierarchy
For any folder segment, Next.js composes the component tree in the following strict order:
<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/analyticsto/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:
- CSS enter/exit animations that must trigger on every page transition.
- Features relying on
useEffectfiring on navigation (e.g., page view telemetry). - Resetting user inputs (e.g., feedback modal forms that must wipe on navigation).
Architectural Diagram: App Router Component Nesting Hierarchy
┌────────────────────────────────────────────────────────────────────────┐
│ NESTED SEGMENT COMPONENT HIERARCHY │
└────────────────────────────────────────────────────────────────────────┘
Nested segment app/dashboard/ (inside the root segment):
<RootLayout> [app/layout.tsx: persistent outer shell]
<ErrorBoundary fallback={<Error />}> [app/error.tsx: catches errors in child segments]
<Suspense fallback={<Loading />}> [app/loading.tsx: streams the child's fallback]
<Layout> [app/dashboard/layout.tsx: persists state]
<Template> [app/dashboard/template.tsx: remounts on navigation]
<ErrorBoundary fallback={<Error />}> [app/dashboard/error.tsx]
<Suspense fallback={<Loading />}> [app/dashboard/loading.tsx]
<Page /> [app/dashboard/page.tsx: active leaf]
</Suspense>
</ErrorBoundary>
</Template>
</Layout>
</Suspense>
</ErrorBoundary>
</RootLayout>
Within one segment the order is Layout > Template > ErrorBoundary > Suspense > Page,
so a segment's error.tsx cannot catch errors thrown by its own layout.tsx; the
parent segment's error.tsx does.
Key Architectural Invariant:
* Layout.tsx retains component state, keeps scroll position, and does NOT re-render on leaf navigation.
* Template.tsx creates a new React key on every navigation, resetting state, DOM elements, and effects.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.
Next.js Layout vs Template Interview Questions
Can a layout be an async Server Component that fetches data?
Yes. Layouts can be async Server Components that query databases or APIs directly.
What is the root layout in Next.js?
The root layout (app/layout.tsx) is required in every App Router application and must define the <html> and <body> tags.
How do you trigger page transition animations in App Router?
Use template.tsx with Framer Motion or CSS animation classes, as templates remount on every navigation.
Can a template and a layout exist in the same folder?
Yes. If both are defined, Next.js renders the layout as the parent wrapping the template.
More Next.js interview questions for freshers
