Next.js
Link and Navigation
Build fast client-side navigation between NewsWave pages using Next.js Link component and router hooks
The web was built on links. Every click, every navigation, every journey between pages depends on them. But traditional HTML links reload the entire page. The browser throws away everything — JavaScript state, loaded images, cached data — and starts fresh. It works, but it's slow and jarring for users. Next.js changes this completely. The Link component looks like a regular HTML link to search engines and screen readers. But behind the scenes, it performs client-side navigation. No page reload. No flash of white. Just instant transitions between pages that feel like a native app. Think of it like the difference between tearing down a house and rebuilding it versus just redecorating the rooms. Traditional links tear down and rebuild. Next.js links just swap the content while keeping everything else intact.Why Client-Side Navigation Matters
Your users don't think about navigation — they just expect it to work instantly. When someone clicks from the NewsWave homepage to an article, they want to see that article immediately. Not after a loading spinner. Not after a white flash. Right now. Client-side navigation makes this possible by downloading JavaScript bundles in advance. Next.js can predict what pages users might visit next and preload them silently in the background. When they finally click, the content is already there waiting. This preloading happens automatically with Link components. Every Link you see on screen gets its JavaScript prefetched when the browser has spare time. It's like having a really good assistant who anticipates your needs before you ask. The performance difference is dramatic. Traditional multi-page applications might take 500-1000ms per navigation. Client-side routing can happen in under 100ms. That's the difference between feeling fast and feeling instant.Real-World Example
GitHub uses client-side navigation extensively. Notice how clicking between repository tabs or files happens instantly without page reloads. Same with Twitter's timeline navigation. Next.js Link gives you this same experience automatically.
The Next.js Link Component
The Link component wraps regular anchor tags with client-side navigation superpowers. You import it from Next.js, wrap your links, and everything else happens automatically. Prefetching, route transitions, browser history — all handled behind the scenes. Here's how it works in your NewsWave navigation. Start with the basic import and a simple link to the articles page:// Import Link from Next.js for client-side navigation
import Link from 'next/link'
export default function Navigation() {
return (
<nav>
{/* Link wraps anchor tag for fast navigation */}
<Link href="/articles">Latest Articles</Link>
</nav>
)
}What just happened?
Next.js Link created a navigation link that will use client-side routing instead of full page reloads. The href attribute points to your articles page route. Try this: Create links to different pages and notice how smooth the transitions feel compared to regular HTML links.
// Complete navigation with multiple Link components
import Link from 'next/link'
export default function NewsNavigation() {
return (
<header style={{ background: '#1e293b', padding: '16px 20px' }}>
<nav style={{ display: 'flex', gap: '24px' }}>
{/* Home page link */}
<Link href="/" style={{ color: '#e2e8f0', textDecoration: 'none' }}>
NewsWave Home
</Link>
{/* Category pages */}
<Link href="/category/tech" style={{ color: '#e2e8f0', textDecoration: 'none' }}>
Technology
</Link>
<Link href="/category/business" style={{ color: '#e2e8f0', textDecoration: 'none' }}>
Business
</Link>
</nav>
</header>
)
}What just happened?
You created a navigation header with multiple Link components pointing to different routes. Each link will use client-side navigation and prefetch its target page. The styling works exactly like regular CSS. Try this: Add more category links or a search page link.
Dynamic Links and Route Parameters
Static links are just the beginning. NewsWave needs dynamic links that change based on data — article titles, author names, category filters. These dynamic links still get all the performance benefits of client-side navigation. The key is building href strings dynamically using JavaScript template literals or string concatenation. Next.js handles the routing automatically as long as you have matching dynamic routes in your file structure. Here's how to create article links that use the article slug as a route parameter:// Dynamic article links using template literals
import Link from 'next/link'
export default function ArticleList({ articles }) {
return (
<div>
{articles.map(article => (
<article key={article.id} style={{ marginBottom: '20px', padding: '16px', border: '1px solid #e2e8f0', borderRadius: '8px' }}>
{/* Dynamic link using article slug */}
<Link href={`/articles/${article.slug}`} style={{ textDecoration: 'none' }}>
<h2 style={{ color: '#0f172a', margin: '0 0 8px' }}>{article.title}</h2>
</Link>
<p style={{ color: '#6b7280', margin: 0 }}>{article.excerpt}</p>
</article>
))}
</div>
)
}What just happened?
Each article generates a dynamic link using its slug property. The template literal creates URLs like `/articles/ai-revolution-2024` that match your dynamic route structure. Next.js prefetches these pages automatically. Try this: Add more article data and see how the links generate automatically.
// Category filter links with dynamic routes
import Link from 'next/link'
export default function CategoryTags({ article }) {
return (
<div style={{ display: 'flex', gap: '8px', marginTop: '12px' }}>
{article.categories.map(category => (
<Link
key={category}
href={`/category/${category.toLowerCase()}`}
style={{
background: '#f0f9ff',
color: '#0369a1',
padding: '4px 12px',
borderRadius: '16px',
textDecoration: 'none',
fontSize: '13px',
fontWeight: '600'
}}
>
{category}
</Link>
))}
</div>
)
}What just happened?
Category tags become clickable links that filter articles by category. The `toLowerCase()` method ensures consistent URLs. Each tag links to a category page like `/category/technology`. Try this: Style the tags with hover effects and different colors for different categories.
Programmatic Navigation
Sometimes you need to navigate programmatically — after form submissions, login flows, or search actions. You can't always rely on users clicking Link components. For these cases, Next.js provides the useRouter hook. The useRouter hook gives you access to the router object with methods like push(), replace(), and back(). Think of it as the JavaScript API for navigation. You can trigger route changes from anywhere in your component logic. Here's how programmatic navigation works in a NewsWave search form:// Search form with programmatic navigation
'use client'
import { useRouter } from 'next/navigation'
import { useState } from 'react'
export default function SearchForm() {
const [query, setQuery] = useState('')
const router = useRouter()
// Handle form submission and navigate to search results
const handleSearch = (e) => {
e.preventDefault()
if (query.trim()) {
// Programmatically navigate to search results page
router.push(`/search?q=${encodeURIComponent(query)}`)
}
}
return (
<form onSubmit={handleSearch}>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search NewsWave articles..."
style={{ padding: '8px 12px', borderRadius: '6px', border: '1px solid #d1d5db' }}
/>
<button type="submit" style={{ padding: '8px 16px', background: '#0369a1', color: '#fff', border: 'none', borderRadius: '6px', marginLeft: '8px' }}>
Search
</button>
</form>
)
}What just happened?
The useRouter hook provides programmatic navigation through the router.push() method. Form submission triggers navigation to a search results page with query parameters. The encodeURIComponent() function safely handles special characters in search terms. Try this: Add validation to prevent empty searches or create a loading state during navigation.
Active Link States and Route Information
Navigation feels more professional when users can see where they are. Active link styling shows the current page in navigation menus. Next.js provides several ways to detect the current route and style active links accordingly. The usePathname hook returns the current path, perfect for comparing against link destinations. You can use this to conditionally apply CSS classes or styles to active navigation items. Here's how to build NewsWave navigation with active states:// Navigation with active link highlighting
'use client'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
export default function NavigationWithActive() {
const pathname = usePathname()
// Navigation items with their paths
const navItems = [
{ href: '/', label: 'Home' },
{ href: '/articles', label: 'Articles' },
{ href: '/category/tech', label: 'Technology' },
{ href: '/category/business', label: 'Business' }
]
return (
<nav style={{ display: 'flex', gap: '16px', background: '#f8fafc', padding: '16px', borderRadius: '8px' }}>
{navItems.map(item => {
// Check if current path matches this nav item
const isActive = pathname === item.href
return (
<Link
key={item.href}
href={item.href}
style={{
padding: '8px 16px',
borderRadius: '6px',
textDecoration: 'none',
// Conditional styling based on active state
background: isActive ? '#0369a1' : 'transparent',
color: isActive ? '#fff' : '#64748b',
fontWeight: isActive ? '600' : '400'
}}
>
{item.label}
</Link>
)
})}
</nav>
)
}What just happened?
The usePathname hook provides the current route path for comparison with nav item hrefs. Active links get different styling — blue background and white text versus gray text for inactive links. The conditional styling makes navigation state obvious to users. Try this: Add partial matching for category sections or breadcrumb navigation.
// Search page showing current query parameters
'use client'
import { useSearchParams, usePathname } from 'next/navigation'
export default function SearchPageInfo() {
const searchParams = useSearchParams()
const pathname = usePathname()
// Get current search query from URL
const query = searchParams.get('q')
const category = searchParams.get('category')
return (
<div style={{ background: '#f0f9ff', padding: '16px', borderRadius: '8px', border: '1px solid #bfdbfe' }}>
<h3 style={{ margin: '0 0 12px', color: '#1e40af' }}>Current Route Info</h3>
<p style={{ margin: '4px 0', color: '#374151' }}><strong>Path:</strong> {pathname}</p>
{query && <p style={{ margin: '4px 0', color: '#374151' }}><strong>Search Query:</strong> {query}</p>}
{category && <p style={{ margin: '4px 0', color: '#374151' }}><strong>Category Filter:</strong> {category}</p>}
</div>
)
}What just happened?
The useSearchParams hook extracts query parameters from the URL for use in your components. This is perfect for search pages, filters, or any feature that needs URL state. The pathname and searchParams together give you complete route information. Try this: Build a breadcrumb component or create shareable filtered URLs.
Link Performance and Prefetching
Next.js Link components are performance machines. They don't just navigate — they predict and prepare. Every Link visible on screen automatically prefetches its destination page in the background. This happens during browser idle time, so it never blocks user interactions. This prefetching is intelligent. It only prefetches production builds, not development. It respects user preferences like reduced data usage. And it only prefetches when links enter the viewport — not every link on the entire page. You can control this behavior with Link props. The prefetch prop accepts true, false, or null for different strategies:prefetch={true}
Always prefetch this page, even if not visible. Use for critical user flows.
prefetch={false}
Never prefetch. Use for external links or rarely clicked pages.
prefetch={null} (default)
Smart prefetching only when link becomes visible in viewport.
Data Prefetching
Also prefetches page data like getStaticProps results automatically.
// Strategic prefetching for different link types
import Link from 'next/link'
export default function OptimizedNavigation() {
return (
<div>
{/* High-priority navigation - always prefetch */}
<Link href="/articles" prefetch={true}>
<span style={{ color: '#0369a1', fontWeight: '600' }}>Latest Articles</span>
</Link>
{/* Normal navigation - default smart prefetching */}
<Link href="/category/tech">
<span style={{ color: '#6b7280', marginLeft: '16px' }}>Technology</span>
</Link>
{/* Rarely used pages - no prefetching */}
<Link href="/legal/privacy" prefetch={false}>
<span style={{ color: '#9ca3af', marginLeft: '16px', fontSize: '14px' }}>Privacy Policy</span>
</Link>
</div>
)
}What just happened?
Different prefetch strategies optimize for different use cases. Critical navigation links prefetch immediately for instant loading. Normal links use smart viewport-based prefetching. Legal pages skip prefetching to save bandwidth. This balances performance with resource usage. Try this: Monitor network activity to see prefetching in action or test on slow connections.
Common Prefetching Mistake
Don't set prefetch={true} on every link thinking it makes everything faster. This actually hurts performance by downloading too much unnecessary JavaScript. Use aggressive prefetching only for pages users are very likely to visit next, like "Next Article" or "Continue Reading" links.
File Structure for Navigation
Your Next.js file structure determines what routes exist and how navigation works. Every page.js file in the app directory creates a route. Every folder creates a URL segment. Understanding this relationship helps you plan navigation hierarchies effectively. Here's how the NewsWave file structure maps to navigation routes:What just happened?
Each folder in the app directory becomes a URL segment, and each page.js file creates a route at that path. Dynamic segments use brackets like [slug] or [name] to capture URL parameters. This file-based routing system makes navigation structure predictable and easy to organize. Try this: Create additional category folders or add author pages with their own dynamic routes.
Quiz
1. The NewsWave team wants to improve page load times when users click between articles. What does the Next.js Link component provide that regular HTML anchor tags don't?
2. Your NewsWave search form needs to navigate programmatically after the user submits a search query. Which Next.js approach correctly handles this navigation?
3. NewsWave has a privacy policy link in the footer that users rarely click. To optimize bandwidth usage, which Link prop should you use?
Up Next: Static Assets
Learn how Next.js optimizes images, fonts, and static files with automatic compression and CDN delivery for blazing-fast NewsWave performance.