Next.jsMedium
What is the template.js file and how does it differ from layout.js?
template.js wraps its segment's children like a layout, but it creates a new instance on every navigation. State resets, effects re-run and DOM elements are recreated. A layout.js persists across navigations.
Rendering order
When both exist in a segment, the layout wraps the template:
<Layout><Template key={routeParam}>{children}</Template></Layout>
The template gets a unique key per route (based on its child segment), so React remounts it when that key changes.
When to use a template
- Enter animations that must play on every page change (a CSS or Framer Motion fade-in).
- Effects that should run per page, such as logging a page view or resetting focus.
- Resetting state on navigation, for example clearing a feedback form when moving between articles.
- Resetting a
<Suspense>boundary so its fallback shows on every navigation. Layouts only show the fallback the first time.
When to use a layout
Almost always. Shared navigation, sidebars and anything that should keep state or avoid re-rendering belongs in a layout.
Modern alternatives
- React View Transitions (stable in React 19.3, used by Next.js 16.4) can animate route changes without remounting, via
<ViewTransition>and thetransitionTypesprop on<Link>. - With Cache Components, Next.js keeps previous pages alive in a hidden React
<Activity>, so pages also keep state when you go back. A template is still the explicit way to force a reset.
Code example
tsx
1// app/blog/template.tsx2"use client";34import { useEffect } from "react";56export default function BlogTemplate({ children }: { children: React.ReactNode }) {7 useEffect(() => {8 // Runs on every navigation between blog posts (a layout would run once)9 window.scrollTo({ top: 0 });10 console.log("page view", window.location.pathname);11 }, []);1213 return <div className="animate-[fadeIn_200ms_ease-out]">{children}</div>;14}1516// app/blog/layout.tsx - persists, never remounts between posts17// export default function BlogLayout({ children }) {18// return <section><aside>Categories</aside>{children}</section>;19// }2021// Resulting tree for /blog/a -> /blog/b:22// <BlogLayout> kept23// <BlogTemplate key="b"> new instance, effect runs again24// <Page />
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.