Layouts, pages, and navigation
Use route composition to control state lifetime, shared UI and navigation behavior instead of treating every screen as a fresh application.
What you will be able to do
- Map route segments to pages, layouts and templates.
- Predict which state can survive sibling navigation.
- Choose links, programmatic navigation and redirects from intent.
A route is a tree of nested responsibilities
An app directory is not simply a list of independent screens. A matched URL selects page content inside the layouts of its route segments. A root layout establishes the document structure. A catalogue layout might add navigation or a persistent cart summary. The page supplies the route-specific main content. Keep these responsibilities visible in the folder structure so one route change does not require copying the entire shell.
A layout can remain mounted while a nested page changes. This is valuable for expensive shared UI and for intentionally persistent client state. It is also a source of stale assumptions: a layout is not a reliable place to observe every query-string change. Put query-dependent reads in the appropriate page or client navigation hook rather than assuming the whole tree reruns for every URL update.
State lifetime follows component identity
A text input inside a persistent layout can keep its draft while the user moves between sibling routes. A template creates a new instance for its children when the relevant navigation changes its identity, which is useful when state should reset. Neither behavior is automatically preferable. Decide whether the product wants continuity, a clean form or an explicit unsaved-changes prompt, then place the owner accordingly.
The kata models layouts as a path of IDs. The longest shared prefix represents layouts that can be retained for the simplified navigation. Everything after that prefix unmounts from deepest to shallowest on the old side and mounts from shallowest to deepest on the new side. This is a reasoning exercise, not Next.js internal reconciliation. Actual route groups, templates and keys can introduce additional identity boundaries.
Choose navigation APIs by the job they perform
Use a link for a destination the user can navigate to. A real anchor supports opening in a new tab, copying its address and keyboard interaction; Next Link adds framework navigation behavior. Use programmatic navigation after an event when the destination is a result of that event. A server redirect expresses a server-side routing decision, such as moving the user after a successful mutation.
Distinguish push from replace by history semantics. A normal move to a product can add an entry. Correcting an invalid URL or redirecting after a transient step may replace it. Do not put a div with an onClick handler where a link belongs, and do not pass untrusted arbitrary destinations to navigation APIs. A redirect is a control-flow outcome, so broad exception handlers should not accidentally swallow it.
Server execution
import Link from 'next/link';
import type { ReactNode } from 'react';
export default function CatalogueLayout({ children }: { children: ReactNode }) {
return <section>
<nav aria-label="Catalogue navigation">
<Link href="/catalog">All products</Link>
{' '}
<Link href="/cart">Cart</Link>
</nav>
{children}
</section>;
}Test the complete navigation experience
Test a route by direct URL entry as well as internal navigation. A working Link click can depend on already loaded client state that a fresh visit does not have. Then test browser Back, reload and an unknown route. Add a draft input in a temporary shared layout and observe when it resets. You should be able to explain each result from component placement rather than from trial-and-error use of persistence libraries.
Navigation also affects accessibility. The destination needs a useful title and meaningful heading, and controls must retain valid semantics. If a dialog or focus-managed widget is open during a route change, define where focus should move or return. In an interview, connect the route tree to state lifetime and user navigation behavior. Saying only that routing is file based leaves the important design decisions unexplained.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGELayouts rerun with every page query-string change, so they are the universal place for filter reads.
- A more accurate model
Persistent layouts should not be assumed to observe every query change. Put query-dependent reads in the page or an appropriate client navigation hook.
- How to check it
N03 and N04 describe layout persistence and navigation; the layout lesson separates shell ownership from query-dependent content.
- CLAIM TO CHALLENGEA div with onClick is equivalent to a destination link.
- A more accurate model
A link provides keyboard and browser affordances such as copying the address and opening a new tab. Use a semantic destination control.
- How to check it
N04 covers linking and navigation; the lab checks ordinary link behavior as well as activation.
Mistakes to catch in your own code
- Persistent layouts should not be assumed to receive fresh page search parameters on every navigation.
- Do not choose templates merely to force rerenders without understanding the intended state reset.
- A clickable div loses important link behavior.
Write it by hand
JavaScript logic playground
Find retained layout boundaries
Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.
- Implement solve({from,to}). Each input is an array of layout IDs ordered from root to leaf. The shared prefix is retained.
- Return {retained,unmounted,mounted}. Unmount the old unmatched suffix from deepest to shallowest; mount the new suffix from shallowest to deepest.
- This is a simplified identity model for reasoning. It does not inspect a real Next.js route tree.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 4 test cases
- Sibling pages share shell
Input
{ "from": [ "root", "shop", "detail" ], "to": [ "root", "shop", "list" ] }Expected
{ "retained": [ "root", "shop" ], "unmounted": [ "detail" ], "mounted": [ "list" ] } - Deeper navigation
Input
{ "from": [ "root", "shop" ], "to": [ "root", "shop", "reviews" ] }Expected
{ "retained": [ "root", "shop" ], "unmounted": [], "mounted": [ "reviews" ] } - Different branches unwind fully
Input
{ "from": [ "root", "shop", "detail" ], "to": [ "root", "admin", "users" ] }Expected
{ "retained": [ "root" ], "unmounted": [ "detail", "shop" ], "mounted": [ "admin", "users" ] } - Identical tree
Input
{ "from": [ "root" ], "to": [ "root" ] }Expected
{ "retained": [ "root" ], "unmounted": [], "mounted": [] }
Reveal the worked solution and reasoning
function solve(input) {
let shared = 0;
while (shared < input.from.length && shared < input.to.length && input.from[shared] === input.to[shared]) shared++;
return {
retained: input.from.slice(0, shared),
unmounted: input.from.slice(shared).reverse(),
mounted: input.to.slice(shared)
};
}Only a prefix is retained: an equal label below a different parent is not automatically the same mounted instance.
The order matters when reasoning about nested cleanup and setup, but React and Next.js behavior must still be inspected in the real lab.
Verify it in a real Next.js application
Next.js application lab
Observe layout-owned state and route changes
Open the local application route /catalog after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Inspect app/layout.tsx, app/catalog/layout.tsx, the product page and the @modal slot. Map URL segments, shared layout boundaries and parallel rendering separately.
- Add a temporary client counter or draft input to the shared root layout. Navigate from /catalog to /cart, /hydration and back, then compare a full reload.
- In a separate experiment, place the temporary owner inside a route page or a template, keeping all required providers intact. Compare which navigations now replace that owner.
- Remove the temporary instrumentation and verify normal links, Back, direct product URLs and skip-link navigation still work.
Check the behavior
- The shared navigation remains available while destination main headings identify the active route.
- Observed state lifetime matches the placement of its owner.
- A full reload and an internal navigation are reported as different lifecycle observations.
- The destination controls support keyboard activation and ordinary link behavior.
Review the application reasoning
A layout experiment should compare one changed boundary at a time; persistence can otherwise make a remount look like retained component state.
Restore the intended owner afterward. Forced remounts should solve a stated lifetime requirement, not conceal an unexplained synchronization bug.
Open the project files and run instructions
A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.
The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.
cd nextjs-interview-lab
npm ci
npm run dev
# In a second terminal
npm test
# Stop dev, then verify the production application
npm run build
npm start
# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2eOpen http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.
Explain it in an interview
Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.
01How is a template different from a layout?
A layout is intended to share UI across nested routes and can preserve mounted state. A template introduces a fresh instance for its relevant navigation, so its child state and Effects reset. I choose between them from the intended lifetime of a draft or widget, then verify actual navigation behavior.
Follow-up questions
- Where should an unsaved form live?
- How would a key affect the same problem?
- Layouts and pagesOfficial documentation
- CompleteFrontend Next.js question bankPublisher practice bank
02When do you use Link instead of router.push?
For a normal destination I use Link so the control remains a semantic link with browser affordances. Programmatic navigation fits a result of an event, such as a completed workflow. I also specify whether the action should add history or replace the current entry.
Follow-up questions
- Can the user open it in a new tab?
- What makes a destination untrusted?
- Linking and navigatingOfficial documentation
03Why did state survive navigation but disappear on reload?
The component owning the state stayed mounted during the client navigation, but a reload constructed a new document and component tree. In-memory persistence across a shared layout is different from durable storage. If reload persistence is required, I would explicitly initialize from a validated storage or server source.
Follow-up questions
- What changes if the provider moves into the page?
- How does initialization affect hydration?
- Layouts and pagesOfficial documentation
- React: scaling up with reducer and contextOfficial documentation
04Why test a route both directly and through navigation?
The first visit must construct the route without prior client state, whereas navigation can reuse layouts, cached route data and loaded modules. Testing both detects hidden dependencies on previous visits, missing standalone route behavior and incorrect state retention. Back and refresh exercise additional user-visible cases.
Follow-up questions
- What does an intercepted route show on refresh?
- How can prefetch change the trace?
- Linking and navigatingOfficial documentation
- CompleteFrontend Next.js question bankPublisher practice bank
Check your understanding
Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.
Your checkpoint
Loading your local progress.
Sources and further reading
- Layouts and pagesOfficial documentation
- Linking and navigatingOfficial documentation
- React: scaling up with reducer and contextOfficial documentation
- SimplifyJobs frontend assessmentEmployer assignment
- CompleteFrontend Next.js question bankPublisher practice bank