Topic 12 of 39
Linking & Navigation
Overview
Next.js provides the <Link> component and useRouter hook for client-side navigation. <Link> automatically prefetches the linked page in the background, making navigation nearly instantaneous.
Syntax
tsx
import Link from 'next/link';
import { useRouter } from 'next/navigation';
export default function Nav() {
const router = useRouter();
return (
<nav>
{/* Declarative Navigation (Prefetches by default) */}
<Link href="/about">About Us</Link>
{/* Programmatic Navigation */}
<button onClick={() => router.push('/dashboard')}>
Go to Dashboard
</button>
</nav>
);
}Common Pitfalls
- Using standard
<a>tags for internal links instead of<Link>, which causes full page reloads and ruins SPA performance. - Importing
useRouterfromnext/router(Pages router) instead ofnext/navigationin the App Router. - Trying to use
useRouterin a Server Component (it requires 'use client').
Interview Questions
Q:
How does the Next.js
<Link> component optimize performance?A:
It automatically prefetches the code and data for the linked route in the background when the link scrolls into the user's viewport. When clicked, the page transition is instant.
Real-World Example
Conditionally applying active styles to navigation links based on the current path.
example
tsx
'use client';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
export default function Navigation() {
const pathname = usePathname();
return (
<Link
href="/dashboard"
className={pathname === '/dashboard' ? 'text-blue-500 font-bold' : 'text-gray-500'}
>
Dashboard
</Link>
);
}Check Your Knowledge
Test your understanding of Linking & Navigation with these quick questions.