🚀 Next.js Routing: Link and Navigation
The Magic Doorways of Your App
Imagine your Next.js app is a magical house with many rooms. Each room is a page. But how do you move between rooms? You need doorways! In Next.js, the <Link> component and navigation tools are your magical doorways.
🔗 The Link Component
What is it?
The Link component is like a super-powered door in your house. When you click it, you zoom to another room instantly—no need to rebuild the entire house!
Why is it special?
Regular HTML links (<a> tags) make the browser reload everything. That’s slow! The Link component only updates what changed. It’s like teleporting instead of walking.
import Link from 'next/link'
function Menu() {
return (
<nav>
<Link href="/">Home</Link>
<Link href="/about">About</Link>
<Link href="/blog">Blog</Link>
</nav>
)
}
🧒 Simple Explanation
Think of it like this:
- Regular link = Walking to school (slow, tiring)
- Link component = Teleporting to school (instant, magical!)
Key Features
| Feature | What it does |
|---|---|
href |
Where you want to go |
replace |
Don’t add to history |
scroll |
Control scroll position |
prefetch |
Load page ahead of time |
🎮 Programmatic Navigation
What is it?
Sometimes you don’t want a clickable link. You want to move to a new page after something happens—like after submitting a form or clicking a button.
This is called programmatic navigation. You’re writing code that says “Go here NOW!”
'use client'
import { useRouter } from 'next/navigation'
function LoginButton() {
const router = useRouter()
function handleLogin() {
// After login succeeds...
router.push('/dashboard')
}
return (
<button onClick={handleLogin}>
Login
</button>
)
}
🧒 Simple Explanation
Imagine you’re playing a video game. When you beat a level, the game automatically takes you to the next level. You didn’t click a link—the game decided to move you!
🪝 The useRouter Hook
What is it?
useRouter is your navigation remote control. It gives you buttons to:
- Go forward
- Go back
- Push to a new page
- Replace the current page
- Refresh the page
'use client'
import { useRouter } from 'next/navigation'
function NavigationDemo() {
const router = useRouter()
return (
<div>
<button onClick={() => router.push('/new')}>
Go to New Page
</button>
<button onClick={() => router.back()}>
Go Back
</button>
<button onClick={() => router.refresh()}>
Refresh
</button>
</div>
)
}
Available Methods
graph LR A[useRouter] --> B[push] A --> C[replace] A --> D[back] A --> E[forward] A --> F[refresh] A --> G[prefetch] B --> B1[Go to new page] C --> C1[Replace current page] D --> D1[Go to previous page] E --> E1[Go forward in history] F --> F1[Refresh current page] G --> G1[Pre-load a page]
🧒 Simple Explanation
It’s like having a TV remote but for your website:
- Push = Change channel (new page)
- Back = Previous channel
- Refresh = Restart current show
⚡ Prefetching Strategies
What is it?
Prefetching is like your app being super smart and loading pages before you click on them. So when you DO click, it appears instantly!
How it works
// Automatic prefetching (default)
<Link href="/about">About</Link>
// Disable prefetching
<Link href="/about" prefetch={false}>
About
</Link>
// Manual prefetching
const router = useRouter()
router.prefetch('/dashboard')
When does prefetching happen?
graph TD A[Link appears on screen] --> B{Is it visible?} B -->|Yes| C[Start prefetching] B -->|No| D[Wait until visible] C --> E[Page loads in background] E --> F[User clicks] F --> G[Instant navigation! ⚡]
🧒 Simple Explanation
It’s like when your mom packs your lunch the night before school. When morning comes, everything is ready—you don’t have to wait!
Prefetch Options
| Setting | Behavior |
|---|---|
true |
Always prefetch |
false |
Never prefetch |
null (default) |
Prefetch when visible |
🧈 Soft Navigation
What is it?
Soft navigation means moving between pages without reloading the whole app. Only the parts that changed get updated.
Why it matters
- ✅ Shared layouts stay the same
- ✅ State is preserved
- ✅ Super fast transitions
- ✅ Smooth user experience
// This triggers SOFT navigation
<Link href="/about">About</Link>
// The header and footer stay!
// Only the page content changes.
🧒 Simple Explanation
Imagine changing your shirt but keeping your pants and shoes on. You don’t have to get completely undressed and dressed again—just swap the shirt!
Visual Flow
graph TD A[Current Page] --> B[Click Link] B --> C{What changes?} C --> D[Keep: Layout, Header, Footer] C --> E[Update: Page Content Only] D --> F[Smooth Transition ✨] E --> F
🔨 Hard Navigation
What is it?
Hard navigation is a full page reload. Everything gets thrown away and rebuilt from scratch.
When does it happen?
- Browser back/forward buttons (sometimes)
- Full page refresh (F5)
- Regular
<a>tags withoutLink - Server-side redirects
// This causes HARD navigation
<a href="/about">About (slow!)</a>
// This is SOFT navigation
<Link href="/about">About (fast!)</Link>
🧒 Simple Explanation
Hard navigation is like demolishing your LEGO house and rebuilding it completely, instead of just moving a few blocks around.
Soft vs Hard Comparison
| Aspect | Soft ✅ | Hard ❌ |
|---|---|---|
| Speed | Fast | Slow |
| State | Preserved | Lost |
| Layout | Reused | Rebuilt |
| Network | Minimal | Full reload |
🎯 Layout Deduplication
What is it?
Next.js is smart! When you navigate between pages that share a layout, it doesn’t reload the layout. It only updates what’s different.
How it works
app/
├── layout.js ← Root layout (never reloads)
├── page.js
└── blog/
├── layout.js ← Blog layout
├── page.js
└── [slug]/
└── page.js
// app/layout.js (stays the same)
export default function RootLayout({ children }) {
return (
<html>
<body>
<Header /> {/* Never re-renders! */}
{children} {/* Only this changes */}
<Footer /> {/* Never re-renders! */}
</body>
</html>
)
}
🧒 Simple Explanation
It’s like your house frame stays the same, but you can change the furniture inside each room. You don’t rebuild the walls every time you want a new couch!
Visual Flow
graph TD A[Navigate from /blog to /about] A --> B[Check layouts] B --> C{Same Root Layout?} C -->|Yes| D[Keep Root Layout ✅] C -->|No| E[Replace Layout] D --> F[Only update page content] F --> G[Fast Navigation! ⚡]
✨ View Transitions
What is it?
View Transitions make page changes look beautiful with smooth animations. Instead of instant swaps, elements can fade, slide, or morph into new positions.
Enabling View Transitions
// next.config.js
module.exports = {
experimental: {
viewTransition: true
}
}
Using View Transitions
'use client'
import { useRouter } from 'next/navigation'
import { unstable_ViewTransition as ViewTransition }
from 'react'
function Card({ id, title }) {
const router = useRouter()
function handleClick() {
router.push(`/item/${id}`)
}
return (
<ViewTransition name={`card-${id}`}>
<div onClick={handleClick}>
<h3>{title}</h3>
</div>
</ViewTransition>
)
}
🧒 Simple Explanation
It’s like magic scene transitions in movies. Instead of just cutting to the next scene, things smoothly fade and move into place. It makes your app feel like a movie!
Animation Types
| Transition | Effect |
|---|---|
fade |
Elements smoothly appear/disappear |
slide |
Elements slide in from a direction |
morph |
Elements transform shape/position |
cross-fade |
Old and new blend together |
🎁 Quick Summary
| Concept | What it does | Everyday analogy |
|---|---|---|
| Link | Clickable navigation | Magic teleport door |
| Programmatic Nav | Code-triggered navigation | Auto-pilot |
| useRouter | Navigation remote control | TV remote |
| Prefetching | Pre-load pages | Packing lunch early |
| Soft Navigation | Partial updates only | Changing your shirt |
| Hard Navigation | Full page reload | Rebuilding the house |
| Layout Dedup | Reuse shared layouts | Keep the house frame |
| View Transitions | Animated page changes | Movie scene transitions |
🚀 You’ve Got This!
Navigation in Next.js is all about making your app feel fast and smooth. The tools are simple:
- Use
<Link>for clickable navigation - Use
useRouter()when code needs to navigate - Let prefetching make everything instant
- Enjoy smooth transitions with View Transitions
Now go build something amazing! 🎉