Loading lessons...
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 / Scenario | Use layout.tsx | Use template.tsx |
|---|---|---|
| Persistent navigation bars / sidebars | Yes | No |
| CSS enter / exit transition animations | No | Yes |
Resetting useState on every sub-route change | No | Yes |
| Analytics pageview tracking per page visit | No | Yes |
| Per-page feedback or contact forms resetting state | No | Yes |
TL;DR
template.tsxcreates a brand new instance on every route transition.layout.tsxstays mounted and preserves internal state across navigations.- Use
template.tsxfor CSS page transition animations or resetting component state. - Templates are rendered inside layouts and wrap child pages.