What is the difference between a layout and a template in the Next.js App Router?
Short answer
A layout preserves its state and does not re-render when navigating between pages that share it, while a template, defined in a template.js file, creates a fresh instance and re-renders every time you navigate, which is useful when you want an animation or effect to run again on…
Advertisement
AModel answer
A layout preserves its state and does not re-render when navigating between pages that share it, while a template, defined in a template.js file, creates a fresh instance and re-renders every time you navigate, which is useful when you want an animation or effect to run again on every page change.
// app/blog/template.js
export default function BlogTemplate({ children }) {
return <div className="fade-in">{children}</div>;
}Real-world example
A blog uses a template to replay a subtle fade in animation every time a reader navigates to a different article, since a regular layout would not re-run that animation on each navigation.
Likely follow-ups
- When would you choose a template over a layout?
- Can a route have both a layout and a template at the same time?
Related topics