Topic 14 of 39
Page Templates
Overview
Templates (template.tsx) are similar to Layouts in that they wrap children. However, unlike layouts, templates create a NEW instance for each of their children on navigation. This means DOM elements are recreated and state is reset.
Syntax
tsx
// app/template.tsx
'use client';
import { motion } from 'framer-motion';
export default function Template({ children }: { children: React.ReactNode }) {
// This animation will trigger on EVERY route change
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
>
{children}
</motion.div>
);
}Common Pitfalls
- Using a template when you actually wanted state to persist (use a layout instead).
- Overusing templates, which can hurt performance because they force React to unmount and remount the DOM on every navigation.
Interview Questions
Q:
When should you use
template.tsx instead of layout.tsx?A:
Use template.tsx when you want to reset state or trigger animations on navigation. For example, triggering a page transition animation or resetting a form state when navigating between identical route structures.
Real-World Example
Triggering a page entry animation using Framer Motion when a user navigates between routes.
example
tsx
// The syntax block above is the standard real-world example for templates.
// Layouts keep the DOM stable, Templates recreate it.Check Your Knowledge
Test your understanding of Page Templates with these quick questions.