Question presented to candidate:
"Both layout.tsx and template.tsx wrap the pages in a folder. What is the actual difference, and when would you reach for a template instead of a layout?"
What a strong answer should cover:
- A layout is mounted once and kept across navigations between its child routes, so Client Component state, DOM and running effects survive.
- A template sits in the same place in the tree but gets a unique key per child segment, so it and everything under it remount: state resets, effects run again, the DOM is recreated.
- The nesting order: layout wraps template, template wraps error, loading, not-found and page.
- Use cases for a template: per-page enter animations, effects that must re-run on each navigation (logging, focus), forms that must start empty, showing a Suspense fallback on every navigation.
- Search-param-only changes do not remount a template; only a change of its own child segment (including dynamic params) does.
- Both are Server Components by default and both receive
children; prefer a layout and treat a template as the exception.
Clarifying questions expected:
- "Is the state that should reset local to one component?" β a
keyon that component may be enough, without a template. - "Is Cache Components enabled?" β then pages are kept alive with React Activity, which changes what "navigating away" means for state.
Code / implementation expected: Yes β a layout with a persistent input and a template with an effect that logs each page view.