CodePark/ questions / App Router & files
START PRACTICINGPRACTICE
Frontend question · Next.js › App Router & files

What is the difference between layout.tsx and template.tsx? When would you use a template?

// app/dashboard/template.tsx
"use client";
import { useEffect } from "react";

export default function Template({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    logPageView(); // runs on every navigation
  }, []);
  return <div className="fade-in">{children}</div>;
}

A layout stays mounted when you move between pages that share it. A template remounts on every navigation.

With a layout, React keeps the same component instance. So state survives, such as an open sidebar or text in a search input. Effects inside the layout do not run again.

A template wraps its children the same way. But Next.js gives it a new key for each route, so React throws it away and builds a new one on every navigation. As a result:

  • client state inside it resets
  • DOM elements are created again
  • effects run again

Use a template when you want that reset. Examples:

  • an enter animation for each page
  • logging a page view in useEffect
  • a form that should start empty on each route

In most cases a layout is the right choice.

  • Layouts stay mounted and keep their state when you navigate between sibling pages.
  • Templates remount on every navigation.
  • Effects inside a template run again for each route.
  • Use templates for per-page animations, page-view logging or resetting state.