tezvyn:

What is layout.js and how does it differ from shared headers?

AI-drafted, machine-checkedSource: nextjs.orgbeginner
WHAT IT TESTS

App Router state preservation and nesting.

ANSWER OUTLINE

layout.js persists across navigations without remounting; a shared header in each page.js remounts and loses state.

RED FLAG

calling them identical or only citing DRY.

WHAT THIS TESTS: This question tests whether you understand the App Router's file-system based layout composition and state preservation guarantees. Interviewers want to know if you grasp that layouts are framework-level primitives, not just a convention for sharing UI.

A GOOD ANSWER COVERS: First, the core mechanism: layout.js exports a component that accepts a children prop and wraps page.js and any nested layouts. Second, state persistence: when a user navigates between sibling routes, Next.js swaps only the page component while keeping the layout mounted, which preserves local state, scroll position, and DOM state. Third, the contrast with manual inclusion: importing a shared Header into every page.js causes React to unmount the old page and mount the new one, which destroys any state inside the header and re-runs layout effects on every navigation. Fourth, nesting: layouts are nested automatically through the segment hierarchy, so each route segment can define its own layout that wraps only its subtree, enabling colocated data fetching and error boundaries. Fifth, performance: avoiding remounting reduces JavaScript execution and layout thrashing during navigation.

COMMON WRONG ANSWERS: A red flag is saying the two approaches are identical or that layout.js is just for DRY code. Another mistake is claiming that layout.js only runs once globally; it actually re-renders when children change, but it does not remount. Some candidates also confuse App Router layouts with Pages Router _app.js, which is a true singleton, whereas App Router layouts compose recursively per segment.

LIKELY FOLLOW-UPS: The interviewer might ask how layout.js interacts with loading.js and error.js, or whether a layout can fetch data and how that data is cached across navigations. They may also ask about the template.js file and when you would use it instead of layout.js, since templates do remount on navigation.

ONE CONCRETE EXAMPLE: Imagine a dashboard with a sidebar navigation. If the sidebar is inside layout.js and the user clicks between Dashboard Home and Settings, the sidebar remains mounted and its expanded or collapsed state persists. If the sidebar were imported into every page.js, the sidebar would unmount and remount, causing a flash, loss of expand state, and re-execution of any entrance animations or data fetching.

Read the original → nextjs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.