Layouts are one of the App Router's most powerful features. A layout.tsx file in any folder defines the chrome that wraps every page beneath that segment, such as a navigation bar, footer, or sidebar. Because layouts persist across navigations between their child routes, React state inside a layout survives route changes, providing a snappy and uninterrupted experience. The root layout located at app/layout.tsx is mandatory and wraps the entire application; it is also where you typically set up the <html> and <body> tags.
Templates look similar to layouts but behave very differently. A template.tsx file creates a new instance on every navigation, which means its effects re-run, its local state resets, and the entire component remounts. This is useful when you want each route to start with fresh state, for example an animation that should replay on each page transition or a form that should clear when the user navigates away and back. Choosing between a layout and a template therefore comes down to whether you want state continuity or fresh state.
Beyond layouts and templates, Next.js recognizes a handful of other special files that improve the user experience. Adding a loading.tsx to a route segment automatically wraps the page in a React Suspense boundary, so Next.js can stream the loading UI while the actual content is still being fetched. An error.tsx file, which must be a Client Component, acts as an error boundary that catches errors in its segment and its children, exposing both the error and a reset function so the user can retry. Finally, not-found.tsx provides a custom 404 page that renders when notFound() is called from a Server Component or when no route matches the requested URL. Streaming ties all of this together: the server can send UI in chunks as it becomes ready, rather than waiting for all data to be available, and Suspense boundaries mark where streamed content can be revealed progressively, improving both Time to First Byte and First Contentful Paint.