The template.js Convention

Like a layout, but intentionally destroys and rebuilds state on navigation.

Next.js5 min readConcept 8 of 65

The anti-layout

The template.js (or .tsx) file convention is the counterpart to layout.js. Like a layout, a template wraps a child segment or page and must accept a {children} prop.

However, there is one massive difference: while layouts persist their state across route changes, templates **create a completely new instance** for each child on navigation.

Why destroy state?

If preserving state is great for performance, why would you ever want a template? Sometimes, you specifically *need* a component to remount from scratch.

Common use cases include: triggering page-transition animations (which require a fresh mount), resetting form inputs when moving between steps in a wizard, or forcing a useEffect to run on every single page view.

Nesting order

You create a template exactly like a layout: export a React component from template.js that renders {children}.

If you place both a layout.js and a template.js in the exact same folder, Next.js enforces a strict nesting order: The Layout will always wrap the Template. <Layout><Template><Page /></Template></Layout>.

Layout vs Template

Type text into both the Layout and Template inputs, then click the navigation buttons. Watch what happens to the state.

Simulate Navigation:
Persists State
layout.tsx
Destroys State
template.tsx
page.tsx (Page A)

Type text into both the layout and template inputs, then navigate. Notice how the Layout preserves your text, while the Template is completely destroyed and rebuilt by Next.js, resetting its input to empty.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the primary difference between a layout.js and a template.js?
  2. 2If a folder contains both a layout.js and a template.js, how does Next.js structure the component tree?

Remember this

  • Templates wrap routes exactly like layouts.
  • Unlike layouts, templates remount and destroy their state on every navigation.
  • Use templates for page transitions or when you explicitly want state to reset.
  • If both exist in a folder, the Layout always wraps the Template.

Done with this concept?

Mark it complete to track your progress. No login needed.