Linking And Navigation
Build fast client-side navigation with Link, prefetching, and programmatic routing APIs.
The Link Component
`<Link href="/about">` renders an anchor with client-side navigation. Next.js prefetches linked routes when they enter the viewport in production, making subsequent navigations feel instant.
Disable prefetch with `prefetch={false}` for rarely visited or auth-gated routes. Use `replace` instead of push when navigation should not add history entries (wizard steps, redirects after form submit).
- Automatic viewport prefetch in production
- prefetch={false} for low-traffic routes
- replace for non-history navigation
import Link from 'next/link';
<Link href="/dashboard" prefetch={true}>Dashboard</Link>useRouter and redirect
`useRouter` from `next/navigation` (App Router) provides `push`, `replace`, `back`, `refresh`, and `forward`. Server Components use `redirect()` from `next/navigation` for server-side redirects after auth checks or mutations.
`redirect()` throws internally — do not wrap in try/catch expecting to handle it. Call after successful server mutations to navigate to success pages.
- useRouter in Client Components
- redirect() in Server Components and Actions
- redirect throws — do not catch
import { redirect } from 'next/navigation';
if (!session) redirect('/login');Active States and Navigation UX
Detect active routes with `usePathname()` — compare against href for nav highlighting. `useSelectedLayoutSegment()` identifies active nested layout segments for tab navigation within sections.
Scroll to top on route change is default for new pages. Preserve scroll with experimental options or custom logic when navigating back through history where restoration is expected.
- usePathname for active link styling
- useSelectedLayoutSegment for nested tabs
- Consider scroll behavior on navigation
External and Dynamic Links
External URLs use standard `<a target="_blank" rel="noopener noreferrer">` — Link is for internal routes. Dynamic hrefs interpolate params: `` href={`/users/${user.id}`} ``.
Type route params with typed routes (experimental) or const route helpers generated from filesystem to prevent broken links during refactors.
- Plain anchor for external URLs
- Template literals for dynamic hrefs
- Typed route helpers prevent broken links
Loading Feedback
Instant prefetch makes loading states less critical for internal nav, but slow server renders still benefit from `loading.tsx` Suspense fallbacks. `useLinkStatus` (experimental) exposes pending state for custom loading indicators on Link clicks.
Combine route-level loading UI with optimistic UI in client components for mutations — navigation loading and mutation loading are separate concerns.
- loading.tsx for route transitions
- Custom pending indicators when needed
- Separate nav loading from mutation loading