Skip to content
Watch the complete Next.js 15 course on YouTube

Templates

This page explains how to use templates in Next.js as an alternative to layouts when you need component remounting between route changes.

Understanding templates

Templates are special files that provide similar functionality to layouts but with one key difference: they remount on each route change. This means:

  • A new template component instance mounts
  • DOM elements are recreated
  • State is reset
  • Effects are re-synchronized

Creating templates

To create a template, export a default React component from a template.js or template.tsx file. Like layouts, templates must accept and render a children prop:

  • Directoryapp
    • Directoryauth
      • Directorylogin
        • page.tsx
      • Directoryregister
        • page.tsx
      • template.tsx
app/auth/template.tsx
export default function Template({ children }: { children: React.ReactNode }) {
return <div>{children}</div>;
}

Templates vs layouts

While layouts preserve state during navigation, templates force a complete remount. Consider this example:

app/auth/layout.tsx
import Link from "next/link";
import { useState } from "react";
export default function AuthLayout({
children,
}: {
children: React.ReactNode;
}) {
const [input, setInput] = useState("");
return (
<div>
<nav>
<Link href="/auth/login">Login</Link>
<Link href="/auth/register">Register</Link>
</nav>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="This state persists in layout"
/>
{children}
</div>
);
}
app/auth/login/page.tsx
export default function LoginPage() {
return (
<div>
<h1>Login Page</h1>
<form>{/* login form */}</form>
</div>
);
}
app/auth/register/page.tsx
export default function RegisterPage() {
return (
<div>
<h1>Register Page</h1>
<form>{/* registration form */}</form>
</div>
);
}

With a layout, the input state persists when clicking between Login and Register links. Rename the layout.tsx file to template.tsx. Navigating between /auth/login and /auth/register now resets the input state giving you a fresh state every time.

Using both templates and layouts

You can use templates alongside layouts in the same route segment. The rendering order is:

  1. Layout component renders
  2. Template component renders within layout
  3. Page components render within template
  • Directoryapp
    • Directoryauth
      • Directorylogin
        • page.tsx
      • Directoryregister
        • page.tsx
      • template.tsx Remounts on route changes
      • layout.tsx Persists across routes

Use cases

Templates are particularly useful for:

  • Enter/exit animations between routes
  • Features requiring effect re-synchronization
  • Components needing fresh state on navigation
  • Any UI that should reset between routes

For most cases, layouts are recommended. Use templates only when component remounting is specifically needed.