What is template.tsx in Next.js?
What is template.tsx
In Next.js, template.tsx:
- wraps child pages as a layout
- BUT unmounts and remounts on every navigation
- is a Server Component by default
The main difference: layout vs template
layout.tsx | template.tsx | |
|---|---|---|
Wraps children | Yes | Yes |
| Preserved between transitions | Yes | No |
| Unmounts on navigation | No | Yes |
| Keeps state | Yes | No |
| Suited for shell UI | Yes | No |
Structure example
txt
app/dashboard/
├─ layout.tsx
├─ template.tsx
├─ page.tsx
└─ settings/page.tsxRender order:
layout → template → page
On transition:
/dashboard → /dashboard/settings
layoutstaystemplateis recreatedpagechanges
Minimal example
tsx
// app/blog/template.tsx
export default function BlogTemplate({
children,
}: {
children: React.ReactNode;
}) {
return <div className="animate-fade-in">{children}</div>;
}Every transition inside /blog/*:
- remounts the template
- restarts the animation
When template.tsx IS needed
1. Transition animations
txt
tabs / wizard / onboarding- the animation needs to restart every time
2. State reset
txt
forms / editors / filters- transition = a clean slate
3. Modal flows / steps
txt
step1 → step2 → step3- each step is initialized from scratch
4. SEO / experiments
- content needs to be recalculated on every visit
When it is NOT needed
- header / sidebar
- tabs that must keep their state
- layout shell
- global context
Use layout.tsx for that
An important nuance about Client Components
If template.tsx is a client component:
tsx
"use client";- all of its state is lost on navigation
- even between neighboring pages
This is a feature, not a bug.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.