Like Layout But Remounts on Every Visit
template.tsx — Fresh Per Navigation
A template is like a layout, except it creates a new component instance on every navigation — useful for entry and exit animations.
What you'll learn
- Create a `template.tsx`
- See the remount-per-navigation behavior
- Decide between `template.tsx` and `layout.tsx`
A template.tsx looks just like a layout.tsx, but it has one key difference: it
remounts on every navigation. That makes it the right choice for things that should
re-run per visit.
The Shape
// app/template.tsx
export default function Template({
children,
}: {
children: React.ReactNode;
}) {
return <div className="page-fade-in">{children}</div>;
} The signature is identical to a layout. The behavior is what differs.
Why Remounting Matters
Layouts persist across navigation. A useState inside a layout keeps its value when
you move between sibling pages. A template throws that state away on each navigation
because it remounts.
This is exactly what you want for:
- CSS enter animations that should replay on every page visit
- Effects that should re-run on each navigation (analytics page-view events)
- Components that intentionally do not preserve client state
A Practical Example
// app/template.tsx
'use client';
import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
export default function Template({
children,
}: {
children: React.ReactNode;
}) {
const pathname = usePathname();
useEffect(() => {
// fires on every navigation because the component remounts
trackPageView(pathname);
}, [pathname]);
return <div>{children}</div>;
}
function trackPageView(path: string) {
console.log('view', path);
} Template vs Layout — How to Choose
- Need shared UI and persistent state? Use
layout.tsx. - Need shared UI that resets on every navigation? Use
template.tsx. - 95% of apps only need layouts. Reach for templates when you actually want the remount.
That wraps the Foundations section. Now we move into routing in depth.
File-Based Routing →