Lesson 5 +10 XP

Templates vs Layouts (template.tsx)

Templates vs Layouts (template.tsx)

While layout.tsx persists state and remains mounted across route changes, Next.js provides template.tsx when you explicitly need components to re-instantiate on every route transition.

How Templates Work

A template wraps a layout or page. When a user navigates between routes that share a template, Next.js mounts a fresh instance of the template component. This resets all state, re-runs effects (useEffect), and creates new DOM nodes.

<Layout>
  {/* Template key changes on route navigation */}
  <Template key={routePath}>
    <Page />
  </Template>
</Layout>

Defining a Template (template.tsx)

A template has the exact same component API as a layout (accepting a children prop):

// app/dashboard/template.tsx
'use client';

import { useEffect } from 'react';

export default function DashboardTemplate({
  children,
}: {
  children: React.ReactNode;
}) {
  useEffect(() => {
    // Executes on EVERY sub-route navigation inside /dashboard
    console.log('Track pageview event');
  }, []);

  return <div className="animate-fade-in">{children}</div>;
}

Layout vs Template Decision Guide

Requirement / ScenarioUse layout.tsxUse template.tsx
Persistent navigation bars / sidebarsYesNo
CSS enter / exit transition animationsNoYes
Resetting useState on every sub-route changeNoYes
Analytics pageview tracking per page visitNoYes
Per-page feedback or contact forms resetting stateNoYes

TL;DR

  • template.tsx creates a brand new instance on every route transition.
  • layout.tsx stays mounted and preserves internal state across navigations.
  • Use template.tsx for CSS page transition animations or resetting component state.
  • Templates are rendered inside layouts and wrap child pages.