Skip to content

Layout State and Template State Have Different Lifetimes

The Course
•
18 min study

The decision

A layout is intended to preserve its client state across navigation within its subtree. A template creates a new instance for the relevant segment, which deliberately resets state and effects.

Read, predict, run

The lab has a root layout with two pages, Home and Other, and a small client Counter in the layout's header. Both pages sit under that layout, so navigating between them keeps the layout mounted, and the counter's state with it.

The contract below states the rule. owner is the file that renders the component, "layout" or "template". withinOwner is true when the navigation goes between two pages that are both under that file, as Home and Other are; it's false when the navigation leaves it, for example to a page under a different root layout:

JavaScript
export function run({ owner, withinOwner }) {
  return owner === "layout" && withinOwner ? "keep" : "reset";
}

Before pressing Run, predict what run returns for {"owner": "layout", "withinOwner": true} and {"owner": "template", "withinOwner": true}, from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

Layout State and Template State Have Different Lifetimes Next.js · 7 files
import "./globals.css"; import Link from "next/link"; import Counter from "./Counter.jsx"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> <nav> <Link href="/">Home</Link> <Link href="/other">Other</Link> </nav> <Counter /> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Layout State and Template State Have Different Lifetimes</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } "use client"; import { useState } from "react"; export default function Counter({ label = "Layout count" }) { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> {label}: {count} </button> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export default function Other() { return ( <main> <h1>Other page</h1> <p>The root layout counter stays mounted.</p> </main> ); } export function run({ owner, withinOwner }) { return owner === "layout" && withinOwner ? "keep" : "reset"; } export const examples = [ [{ owner: "layout", withinOwner: true }, "keep"], [{ owner: "template", withinOwner: true }, "reset"], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
  • Input {"owner": "layout", "withinOwner": true} → "keep".
  • Input {"owner": "template", "withinOwner": true} → "reset".

The case table computes these results on the server side of the simulation. It compares values; it does not prove a production deployment or database works.

See both lifetimes

Add a template next to the layout and watch the two counters disagree:

  1. Create app/template.jsx:

    JavaScript
    import Counter from "./Counter.jsx";
    
    export default function Template({ children }) {
      return (
        <>
          <Counter label="Template count" />
          {children}
        </>
      );
    }
  2. Run. The header shows Layout count: 0, and Template count: 0 sits above the page.

  3. Press Layout count once and Template count twice.

  4. Predict both counts, then follow the Other link.

A layout and a template Next.js · 7 files
import "./globals.css"; import Link from "next/link"; import Counter from "./Counter.jsx"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> <nav> <Link href="/">Home</Link> <Link href="/other">Other</Link> </nav> <Counter /> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Layout State and Template State Have Different Lifetimes</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } "use client"; import { useState } from "react"; export default function Counter({ label = "Layout count" }) { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> {label}: {count} </button> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export default function Other() { return ( <main> <h1>Other page</h1> <p>The root layout counter stays mounted.</p> </main> ); } export function run({ owner, withinOwner }) { return owner === "layout" && withinOwner ? "keep" : "reset"; } export const examples = [ [{ owner: "layout", withinOwner: true }, "keep"], [{ owner: "template", withinOwner: true }, "reset"], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction

Layout count: 1 and Template count: 0. The layout is the same instance on both pages, so its counter keeps its state. A template is created again for every navigation, so the counter inside it starts over, and any effect in it runs again. That's what templates are for: an enter animation, or logging a page view, on every navigation.

The mistake to avoid is the reverse: putting a draft form in a template and losing what someone typed whenever they follow a link.

The failure to avoid

Moving between different root layouts causes a full page load in real Next.js, so even layout state is lost. The simulator resets React state but doesn't reproduce every module-lifetime effect of that reload.

Exercise

Extend the contract

A forced reset flag should reset even state owned by a persistent layout.

Edit lib/contract.js, then rerun the original cases. If the requested rule changes an earlier result, update that expected value deliberately. Keep the other cases. Add the acceptance cases to examples so the preview checks them too.

  • Input {"owner": "layout", "withinOwner": true, "forceReset": true} must return "reset".
Your working space Next.js · 7 files
import "./globals.css"; import Link from "next/link"; import Counter from "./Counter.jsx"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> <nav> <Link href="/">Home</Link> <Link href="/other">Other</Link> </nav> <Counter /> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Layout State and Template State Have Different Lifetimes</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } "use client"; import { useState } from "react"; export default function Counter({ label = "Layout count" }) { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> {label}: {count} </button> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export default function Other() { return ( <main> <h1>Other page</h1> <p>The root layout counter stays mounted.</p> </main> ); } export function run({ owner, withinOwner }) { return owner === "layout" && withinOwner ? "keep" : "reset"; } export const examples = [ [{ owner: "layout", withinOwner: true }, "keep"], [{ owner: "template", withinOwner: true }, "reset"], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

An explicit reset is a product decision that overrides the default lifetime, so it's checked before the ordinary rule rather than mixed into it.

Hint 2: a first step

Apply the explicit reset condition before the ordinary identity policy.

Show one solution

Replace the exported run function and any constants shown here; keep the examples export underneath it. Compare the result with your own approach.

JavaScript
export function run({ owner, withinOwner, forceReset }) {
  return !forceReset && owner === "layout" && withinOwner ? "keep" : "reset";
}

!forceReset && at the front means a forced reset wins whatever the owner and navigation. The ordinary rule is unchanged for every other case. In React, a forced reset is usually a key that changes, such as the item id on an edit form, which makes React treat it as a new component.

Explain it without the code

Name one piece of state that belongs in a layout and one that belongs in a template, and say why.

Going further

Read the Next.js guide for the framework boundary around this rule. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.