Next.js Routing Navigation (Link & useRouter)
Next.js provides dedicated features for client-side navigation, including the <Link> component and routing hooks for programmatic redirects.
1 Link component prefetching and useRouter hook
Common navigation features in Next.js include:
- <Link> Component: Extends standard HTML anchor tags (
<a>) to prefetch linked page assets in the background, making page transitions nearly instantaneous. - useRouter Hook: Allows you to trigger route transitions programmatically inside Client Components (e.g. redirecting a user after a successful login).
- usePathname Hook: Reads the current active URL path (useful for highlighting active links in a navigation menu).
2 Programmatic Navigation in Code
Let's check how to use these navigation methods:
React — Navigation Methods
"use client";
import Link from 'next/link';
import { useRouter, usePathname } from 'next/navigation';
export default function Navbar() {
const router = useRouter();
const currentPath = usePathname();
function handleLogout() {
console.log('Logging out user...');
// Programmatic redirect to home page
router.push('/login');
}
return (
<nav>
<!-- Prefetching anchor -->
<Link href="/dashboard" className={currentPath === '/dashboard' ? 'active' : ''}>
Dashboard
</Link>
<button onClick={handleLogout}>Logout</button>
</nav>
);
}
3 Code Challenge
Challenge: Write a component containing a back button (
<button>) that redirects users to the previous page in their browser history using the router.back() method.