Topic 13 of 39
Root Layouts
Overview
The Root Layout (app/layout.tsx) is a required file at the top level of your app directory. It defines the <html> and <body> tags and applies global UI (like headers/footers) that persist across all routes.
Syntax
tsx
// app/layout.tsx
import './globals.css';
import { Inter } from 'next/font/google';
const inter = Inter({ subsets: ['latin'] });
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={inter.className}>
<Navbar />
{children}
<Footer />
</body>
</html>
);
}Common Pitfalls
- Forgetting to include the
<html>and<body>tags in the root layout (Next.js requires them). - Trying to fetch user-specific data in the root layout without considering caching implications (layouts don't re-render on navigation).
Interview Questions
Q:
What is the difference between
page.tsx and layout.tsx?A:
page.tsx represents the unique content for a specific URL, while layout.tsx is shared UI that wraps the pages inside its directory and its children. Layouts persist across route changes and do not unmount.
Real-World Example
Adding global providers (like Next-Auth or ThemeProvider) to the root layout.
example
tsx
// app/layout.tsx
import { ThemeProvider } from '@/components/ThemeProvider';
export default function RootLayout({ children }) {
return (
<html lang="en" suppressHydrationWarning>
<body>
{/* Wrapping the app in a client context provider */}
<ThemeProvider attribute="class" defaultTheme="system">
{children}
</ThemeProvider>
</body>
</html>
);
}Check Your Knowledge
Test your understanding of Root Layouts with these quick questions.