REACT & NEXT.JS / 5. APP ROUTER & LAYOUTS
Next.js App Router — Layouts, Pages, Loading, Error
File-based routing with nested layouts — the backbone of your app
EXPLANATION
The App Router uses the filesystem as the router. Every folder = route segment, every page.tsx = route. Special files: • page.tsx → the UI for a route, makes it publicly accessible • layout.tsx → wraps page and all children (persists across navigation!) • loading.tsx → shown instantly while page.tsx is loading (Suspense boundary) • error.tsx → shown when page.tsx throws (Error boundary, must be client) • not-found.tsx → shown when notFound() is called • route.ts → API endpoint (no UI) Dynamic routes: • [slug] → /blog/my-post → params.slug = "my-post" • [...slug] → /docs/a/b/c → params.slug = ["a","b","c"] • (group) → route group, doesn't affect URL Layouts are the key feature: they don't unmount when you navigate between pages. This is what makes instant navigation feel smooth — your sidebar and navbar stay mounted. generateStaticParams() → tells Next.js which dynamic routes to pre-render at build time.
DIAGRAM
app/
├── layout.tsx → wraps EVERYTHING (html, body)
├── page.tsx → route: /
├── (marketing)/ → route group (no URL segment)
│ ├── about/page.tsx → route: /about
│ └── blog/
│ ├── layout.tsx → wraps all /blog/* pages
│ ├── page.tsx → route: /blog
│ └── [slug]/
│ ├── page.tsx → route: /blog/:slug
│ └── loading.tsx → shown while page loads
└── dashboard/
├── layout.tsx → sidebar layout for dashboard
├── page.tsx → route: /dashboard
└── settings/
└── page.tsx → route: /dashboard/settings
Navigation: layout.tsx stays mounted, only page.tsx swapsCODE