Next.js Linking and Navigating demonstrates how to route users smoothly between application views without triggering full page browser reloads.
The primary navigation mechanism is the built-in <Link> component exported from next/link. <Link> prefetches route code in the background automatically as links enter the user's viewport.
Replace standard HTML <a> anchor tags with the Next.js <Link> component:
// components/Navbar.tsx
import Link from 'next/link';
export default function Navbar() {
return (
<nav className="flex space-x-4 p-4 bg-white shadow-sm">
<Link href="/" className="hover:text-blue-600 font-medium">
Home
</Link>
<Link href="/about" className="hover:text-blue-600 font-medium">
About
</Link>
<Link href="/dashboard" className="hover:text-blue-600 font-medium">
Dashboard
</Link>
</nav>
);
}
useRouterFor dynamic redirects following actions like form submissions or authentication responses, use the useRouter hook from next/navigation:
// app/login/Form.tsx
'use client';
import { useRouter } from 'next/navigation';
export default function LoginForm() {
const router = useRouter();
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
// Perform authentication logic here...
// Redirect programmatically
router.push('/dashboard');
};
return (
<form onSubmit={handleLogin} className="space-y-4">
<button type="submit" className="px-4 py-2 bg-green-600 text-white rounded">
Log In
</button>
</form>
);
}
Check current URL path names using usePathname to highlight active navigation links:
// components/NavLink.tsx
'use client';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
export default function NavLink({ href, label }: { href: string; label: string }) {
const pathname = usePathname();
const isActive = pathname === href;
return (
<Link
href={href}
className={`px-3 py-1 rounded ${isActive ? 'bg-blue-600 text-white' : 'text-gray-700'}`}
>
{label}
</Link>
);
}
next/navigation: In App Router, always import navigation hooks from next/navigation rather than legacy next/router.prefetch={false} on secondary or rarely clicked footer links to conserve bandwidth.Client-side navigation with <Link> and useRouter delivers instant route changes. Background prefetching keeps transitions fast and responsive.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.