What is the layout.tsx file in Next.js App Router?
Answer
A layout.tsx (or layout.js) file defines a UI that is shared across routes at its level and below. Unlike pages, layouts preserve state and don't re-render when the user navigates between routes sharing that layout — only the page content changes. Root layout (required): // app/layout.tsx export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en"> <body> <Navigation /> {children} <Footer /> </body> </html> ); }. Must contain <html> and <body> tags. Wraps all routes. Nested layouts: app/dashboard/layout.tsx wraps all routes under /dashboard/*. The layout only renders when navigating within its segment. State persistence: since layouts don't unmount during navigation, state (sidebar open/closed, user preferences) persists automatically. Metadata: layouts can export metadata: export const metadata = { title: "My App", description: "..." };. Layout nesting: layouts nest automatically — root layout wraps dashboard layout which wraps the page. All receive the children prop. Template.tsx: similar to layout but re-creates the component on every navigation (state is reset) — use for features that must reset between routes (form state, error boundaries, animation per-page). Passing data to layouts: layouts can fetch their own data. No need to pass from page — layout fetches independently.
Previous
What is the "use client" directive in Next.js?
Next
What is page.tsx in Next.js App Router?