layout.tsx used to define a user interface that is shared with nested routes

On navigation, layouts preserve state, remain interactive, and do not re-render. Layouts can also be nested. The top-most layout is called the Root Layout. The app directory must include a root layout. This required layout is shared across all pages in an application. Root layouts must contain html and body tags. The root layout is a Server Component by default and can not be set to a Client Component. Any route segment can optionally define its own Layout. These layouts will be shared across all pages in that segment. Passing data between a parent layout and its children is not possible. However, you can fetch the same data in a route more than once, and React will automatically dedupe the requests without affecting performance.

Good to know: You should not manually add <head> tags such as <title> and <meta> to root layouts. Instead, you should use the Metadata API which automatically handles advanced requirements such as streaming and de-duplicating <head> elements.

Layouts do not have access to the current route segment(s). To access route segments, you can use useSelectedLayoutSegment or useSelectedLayoutSegments in a Client Component.

Layouts defined inside a folder (e.g. app/dashboard/layout.js) apply to specific route segments (e.g. acme.com/dashboard) and render when those segments are active. By default, layouts in the file hierarchy are nested, which means they wrap child layouts via their children prop.

Templates are similar to layouts in that they wrap each child layout or page. Unlike layouts that persist across routes and maintain state, templates create a new instance for each of their children on navigation. This means that when a user navigates between routes that share a template, a new instance of the component is mounted, DOM elements are recreated, state is not preserved, and effects are re-synchronized.

There may be cases where you need those specific behaviors, and templates would be a more suitable option than layouts. For example:

Enter/exit animations using CSS or animation libraries. Features that rely on useEffect (e.g logging page views) and useState (e.g a per-page feedback form). To change the default framework behavior. For example, Suspense Boundaries inside layouts only show the fallback the first time the Layout is loaded and not when switching pages. For templates, the fallback is shown on each navigation.

A template can be defined by exporting a default React component from a template.js file. The component should accept a children prop which will be nested segments.