Next.js template files that reset state while layouts stay mounted
A Next.js layout keeps sidebar, media, and widget state across routes, while template.tsx remounts forms, effects, motion, and Suspense when the segment changes.
This article is published in English.
Sources: Next.js template.tsx vs layout.tsx: Reset State Without Remounting the Shell
A tester on a Next.js dashboard writes "refund please" in the Orders feedback field, then opens Customers. The same sentence is still there.
The console stayed quiet. Nothing threw. The field just kept the text.
Layouts are built to remember. That memory helps when the chrome around a page should survive a click, and it gets in the way when a field ought to come back empty. template.tsx clears the field and leaves that chrome standing.
State that refuses to clear
With the App Router, each layout encloses the pages nested under it. Moving between those pages does not create the layout again. It remains where it is.
You usually want that:
- The sidebar holds its scroll offset, and any group you expanded stays expanded.
- Audio or video that is already playing continues through the click.
- Costly client widgets skip a rebuild when the route changes.
State stored on the layout sticks too. A form left half filled, a banner the visitor already closed, a counter, and a useEffect that already ran on the first visit all stay unchanged.
Treat UI rendered by a layout as sticky until the visitor leaves that area of the app.
Room, board, lesson
Picture a classroom and the board at the front.
- The layout is the room. Desks, wall posters, and a projector stay put until the day ends.
- The template is the board. It stands in that room, and someone wipes it ahead of the following class.
- The page is whatever is scheduled for that period. A new period swaps it.
Leave the room standing between periods. Only the board gets cleared.
Keep the costly pieces you want to preserve in the layout. Put anything that should begin empty into the template.
Where the template sits
The file lives next to layout.tsx. Its default export receives children, the same prop a layout receives. Under app/dashboard, the wrapper is a div with class dashboard-page, and the page is rendered inside it.
// app/dashboard/template.tsx
export default function Template({ children }: { children: React.ReactNode }) {
return <div className="dashboard-page">{children}</div>;
}
Next.js nests the page inside this component, and nests this component inside the layout, then stamps a distinct key on the template. On the orders route the simplified tree is a DashboardLayout whose child is Template with key set to /dashboard/orders, and that template's child is OrdersPage. A sidebar drawn by the layout can hold its place while the page inside the template starts clean.
// What Next.js builds (simplified)
<DashboardLayout>
<Template key="/dashboard/orders">
<OrdersPage />
</Template>
</DashboardLayout>
The layout remains. The template's key is replaced any time the child route is different.
React reads that changed key as a new instance. The previous instance unmounts, the state it held is discarded, and the DOM nodes are built again.
Nesting has a direction. The template surrounds page.tsx, then loading.tsx, then error.tsx, then not-found.tsx. The layout.tsx in that same folder sits outside the template, so shell state stored there survives.
A form that leaks across pages
The feedback field from the opening is a Client Component with very little in it. It stores a string with useState, starting from '', and renders a controlled textarea that writes each keystroke back into that state.
// app/dashboard/feedback-box.tsx
'use client';
import { useState } from 'react';
export function FeedbackBox() {
const [text, setText] = useState('');
return (
<textarea value={text} onChange={(e) => setText(e.target.value)} />
);
}
Put the box in the layout and the typed text survives every navigation. That layout renders a nav for the sidebar links, a main around children, and FeedbackBox as a sibling of the page, so the box is not swapped when the page is.
// app/dashboard/layout.tsx (Bad: feedback text leaks between pages)
import { FeedbackBox } from './feedback-box';
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
return (
<section>
<nav>{/* sidebar links */}</nav>
<main>{children}</main>
<FeedbackBox />
</section>
);
}
The sidebar belongs in the layout. The box belongs in the template. That template renders children first, then FeedbackBox, with no 'use client' on the template file itself. The box module is already the client boundary.
// app/dashboard/template.tsx (Good: a fresh box on every page)
import { FeedbackBox } from './feedback-box';
export default function Template({ children }: { children: React.ReactNode }) {
return (
<>
{children}
<FeedbackBox />
</>
);
}
The sidebar then keeps whatever state it had. The feedback field opens blank on Orders, on Customers, and on every other dashboard route. Fresh field, same shell.
Which files remount
Each template carries a key for its own segment. "Every click" is too broad a rule.
Picture a root file, app/template.tsx, plus a nested file, app/blog/template.tsx.
- From
/to/about, the leading segment changes, and the root template mounts again. - From
/aboutto/blog, the root template mounts again, and the blog template appears as well. - Opening
/blog/second-postafter/blog/first-postleaves the root template mounted, because you never leftblog. Only the nested template mounts again. - Switching
/blog?page=1over to/blog?page=2mounts nothing again. A changed query string is not a new segment.
A dynamic segment does count. Pass a different slug under /blog/[slug] and the template in the blog folder mounts again.
app/template.tsx at the root does not clear on each click, which is the usual surprise. It clears only after the top segment changes.
Place the file in the segment that should clear. A file above that segment clears more routes than you asked for.
Effects that should run again
A useEffect placed in a layout runs on that layout's mount. Those routes leave the layout mounted, so the effect does not repeat.
TrackView is the version that goes wrong in a layout. It is a Client Component. The effect lists no dependencies, logs the words "page view" plus window.location.pathname, and returns null.
// app/docs/track-view.tsx (Bad when rendered in the layout)
'use client';
import { useEffect } from 'react';
export function TrackView() {
useEffect(() => {
console.log('page view', window.location.pathname);
}, []);
return null;
}
Move TrackView into app/docs/template.tsx and every docs route creates a new instance, so the effect fires on each docs page.
Keep the logger in the layout by reading the path. usePathname, imported from next/navigation, goes into the dependency array, so the log runs on a path change without a fresh layout mount.
// app/docs/track-view.tsx (Good: works from a layout)
'use client';
import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
export function TrackView() {
const pathname = usePathname();
useEffect(() => {
console.log('page view', pathname);
}, [pathname]);
return null;
}
A template discards every bit of state it wraps. A usePathname dependency repeats a single effect and leaves the remaining state in place. When only that effect is stale, the dependency is the smaller edit.
Fade-in on every visit
CSS motion starts when an element is inserted. A wrapper owned by a layout is inserted on the first visit and then left in the DOM, so you see the motion once.
A template builds new DOM nodes on navigation, which is enough for a short entrance. The blog template wraps children in a div whose class is animate-fade-in.
// app/blog/template.tsx
export default function Template({ children }: { children: React.ReactNode }) {
return <div className="animate-fade-in">{children}</div>;
}
The class is defined in app/globals.css. The animation shorthand is fade-in 200ms ease-out. The @keyframes block named fade-in starts at opacity 0 with translateY(4px) and ends at opacity 1 with transform set to none.
/* app/globals.css */
.animate-fade-in {
animation: fade-in 200ms ease-out;
}
@keyframes fade-in {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: none; }
}
The pieces split the work:
- On a blog route change, the wrapper receives a different
key, so React inserts a new node. animate-fade-inruns because that node was just inserted.- The
@keyframesblock stays brief, which keeps the movement from dragging.
Stay under about 250 milliseconds. Once the pause runs longer, people feel the weight on every click.
Fallbacks that come back
A Suspense boundary inside a layout paints its fallback during the initial load and not after. From then on, React leaves the previous UI on screen while the next route arrives behind it.
A template flips that timing. The subtree is a fresh instance after a navigation, so you see that template's fallback again. The reports template imports Suspense and wraps children with a fallback paragraph that says the report is loading.
// app/reports/template.tsx
import { Suspense } from 'react';
export default function Template({ children }: { children: React.ReactNode }) {
return <Suspense fallback={<p>Loading report…</p>}>{children}</Suspense>;
}
Reach for that when leftover UI would mislead, such as a report headed for the current month that still paints the previous month's figures for a beat.
On most routes, loading.tsx is the simpler file to reach for. The template already surrounds that file, so the two can be used together.
Reset one component with a key
A template clears every child it wraps. Sometimes a single component is all that should start over.
React already supports this. Set key to a value that changes at the moment a fresh instance should appear. ResetOnPath is a Client Component: it reads usePathname and renders FeedbackBox with key set to that pathname.
// app/dashboard/reset-on-path.tsx
'use client';
import { usePathname } from 'next/navigation';
import { FeedbackBox } from './feedback-box';
export function ResetOnPath() {
const pathname = usePathname();
return <FeedbackBox key={pathname} />;
}
Render ResetOnPath inside the layout. State everywhere else in that layout stays put.
The same key fills a hole templates leave open. A query string never causes a template to mount again. A filter that should blank out after ?status= updates has to take its key from those params.
Choose a template when an entire region should start empty. Choose a key when only one component should.
On Next.js 16, generated code often puts app/template.tsx around the entire application, or it wipes a form from inside a useEffect. Spell the constraints in the prompt: shells belong in layouts, route params have to be awaited because they are Promises, and a reset should hit only the UI that ought to reset.
Keep the template on the server
A template starts as a Server Component, and a layout does too. You do not add 'use client' on template.tsx.
The expensive version marks the whole file as a client module so one widget can hold state. That file imports useState, keeps an open flag, renders children, and shows a Help button. The button flips the flag, and a paragraph reading "Need help with this page?" appears while the flag is true. The entire wrapper then ships to the browser.
// app/dashboard/template.tsx (Bad: the whole wrapper ships to the client)
'use client';
import { useState } from 'react';
export default function Template({ children }: { children: React.ReactNode }) {
const [open, setOpen] = useState(false);
return (
<>
{children}
<button onClick={() => setOpen(!open)}>Help</button>
{open && <p>Need help with this page?</p>}
</>
);
}
The lighter version stays on the server. It imports HelpToggle from ./help-toggle, renders children, and renders that widget beside them. Only the widget is a Client Component.
// app/dashboard/template.tsx (Good: only the widget is a Client Component)
import { HelpToggle } from './help-toggle';
export default function Template({ children }: { children: React.ReactNode }) {
return (
<>
{children}
<HelpToggle />
</>
);
}
Count the cost of a remount. On each navigation a template throws away what it rendered and builds it again. A chart that is slow to draw, a chat thread, or a playing video will reload on each click if it lives there.
Leave slow-to-recreate UI in the layout. Leave UI that is cheap to recreate, and wrong to preserve, in the template.
Mistakes that show up later
- Shifting the whole shell into the template. Sidebar offset, expanded groups, and every widget start over after a click. Leave the chrome in
layout.tsxand relocate only the bits that should come back empty. - Assuming the root file clears on each route change. It mounts again only after the first URL segment changes. Drop the file into the segment you actually want cleared.
- Assuming a query string will remount the template. It will not. Derive a
keyfrom those params when a form must clear. - Putting
'use client'on the template itself. The file starts as a Server Component. Push interactive code down into a small child. - Reaching for a template when a single effect is stale. A
usePathnamedependency inside the layout repeats that effect and leaves other state untouched. - Parking a player, a chart, or a chat thread in the template. Each navigation builds them again, and the pause is obvious.
- Thinking
template.tsxalso wraps thelayout.tsxbeside it. The wrap covers the route page, the loading UI, the error UI, and the not-found UI. The layout file stays outside.
Questions that come up
Does every app need this file? No. Plenty of apps ship without it. Add the file only after a layout is holding state that should have cleared.
Does the template refetch server data? Server Components nested under it still render for whichever route you opened. The file's real effect is on browser state, on effects, and on DOM nodes.
Can both files share a folder? Yes. In one folder the layout is the outer wrapper and the template is the inner one, around the page. The outer wrapper stays mounted. The inner one resets.
Can an assistant pick the right file? It can, after you name the UI that must survive a click and the UI that must come back empty. Put that split in the prompt so the generated layout still owns the shell and only the right pieces clear.
Before you choose a file
A layout survives navigation and hangs on to its state. Between that layout and the page sits a template. After its segment changes it is given a fresh key, then its children mount again with empty state, effects that run from scratch, and new DOM. A query string does not cause that remount. A template at the root clears only after the leading segment changes. Often a key, or a dependency on usePathname, is the smaller change.
Before you choose a file, ask whether that UI should still be there after the next click. Leftover feedback text and effects that never fire again start showing up in the dashboards you look through.