Navigation Utilities

Loading concept...

🧭 Next.js Navigation Utilities: Your GPS for Moving Around Apps

Imagine you’re in a magical house with many rooms. Each room is a different page in your app. How do you know which room you’re in? How do you find things? How do you move to another room? That’s what Navigation Utilities do in Next.js!


🎯 What We’ll Learn

Think of these tools like special powers:

Tool Superpower
usePathname Tells you which room you’re in
useSearchParams Reads notes left on the door
useParams Reads the room’s name tag
next/navigation The magic toolbox
useSelectedLayoutSegment Knows which floor you’re on
redirect Teleports you to another room

📦 The Magic Toolbox: next/navigation Module

Before we use any power, we need to grab it from the toolbox!

'use client'

import {
  usePathname,
  useSearchParams,
  useParams,
  redirect,
  useSelectedLayoutSegment
} from 'next/navigation'

Why 'use client'? These tools work in the browser (the “client”). It’s like saying “I need to be in the house to use these powers!”


🏠 usePathname Hook: “Where Am I?”

The Story

Imagine you’re blindfolded in that magical house. You ask: “What room am I in?”

usePathname answers: “You’re in the kitchen!” (or /kitchen in URL language)

How It Works

'use client'
import { usePathname } from 'next/navigation'

function RoomSign() {
  const pathname = usePathname()

  return (
    <p>You are here: {pathname}</p>
  )
}

Real Examples

When You’re At usePathname() Returns
myapp.com/ /
myapp.com/shop /shop
myapp.com/shop/toys /shop/toys
myapp.com/user/123 /user/123

🌟 Common Use: Highlight Current Page

'use client'
import { usePathname } from 'next/navigation'
import Link from 'next/link'

function NavMenu() {
  const pathname = usePathname()

  return (
    <nav>
      <Link
        href="/home"
        className={
          pathname === '/home'
            ? 'active'
            : ''
        }
      >
        Home
      </Link>
      <Link
        href="/about"
        className={
          pathname === '/about'
            ? 'active'
            : ''
        }
      >
        About
      </Link>
    </nav>
  )
}

🔍 useSearchParams Hook: “What’s Written on the Note?”

The Story

You walk into a room and find a sticky note on the door:

  • color=blue
  • size=large

That’s a search parameter! The URL looks like: /shop?color=blue&size=large

How It Works

'use client'
import { useSearchParams } from 'next/navigation'

function FilterDisplay() {
  const searchParams = useSearchParams()

  const color = searchParams.get('color')
  const size = searchParams.get('size')

  return (
    <div>
      <p>Color: {color}</p>
      <p>Size: {size}</p>
    </div>
  )
}

Reading the Note

graph LR A["URL: /shop?color=blue&size=large"] --> B[useSearchParams] B --> C["get#40;'color'#41; → 'blue'"] B --> D["get#40;'size'#41; → 'large'"] B --> E["has#40;'color'#41; → true"] B --> F["toString#40;#41; → 'color=blue&size=large'"]

Useful Methods

Method What It Does Example
.get('key') Get one value 'blue'
.has('key') Check if exists true or false
.getAll('key') Get all values ['blue', 'red']
.toString() Full string 'color=blue'

🌟 Real Example: Product Filter

'use client'
import { useSearchParams } from 'next/navigation'

function ProductList() {
  const searchParams = useSearchParams()
  const category = searchParams.get('category')

  if (category === 'toys') {
    return <p>Showing all toys! 🧸</p>
  }

  if (category === 'books') {
    return <p>Showing all books! 📚</p>
  }

  return <p>Showing everything!</p>
}

🏷️ useParams Hook: “What’s the Room’s Name Tag?”

The Story

Some rooms have special name tags. Instead of “Room 1”, “Room 2”, they have:

  • /user/emma → The room for Emma
  • /product/sneakers → The room for Sneakers

These are dynamic parameters - parts of the URL that change!

File Structure Magic

app/
  user/
    [username]/     ← Dynamic!
      page.js
  product/
    [id]/           ← Dynamic!
      page.js

How It Works

'use client'
import { useParams } from 'next/navigation'

// This file is at: app/user/[username]/page.js
function UserProfile() {
  const params = useParams()

  // If URL is /user/emma
  // params = { username: 'emma' }

  return (
    <h1>Welcome, {params.username}!</h1>
  )
}

More Examples

graph TD A["URL: /shop/toys/123"] --> B["File: app/shop/[category]/[id]/page.js"] B --> C[useParams] C --> D["{ category: 'toys', id: '123' }"]
URL File Path useParams() Returns
/user/emma app/user/[username]/page.js { username: 'emma' }
/blog/my-post app/blog/[slug]/page.js { slug: 'my-post' }
/shop/toys/5 app/shop/[cat]/[id]/page.js { cat: 'toys', id: '5' }

🗺️ useSelectedLayoutSegment Hook: “Which Floor Am I On?”

The Story

Imagine a building with many floors. Each floor has many rooms. You’re in a room, but which floor are you on?

This hook tells you the immediate child segment of the current layout.

How It Works

'use client'
import { useSelectedLayoutSegment } from 'next/navigation'

// This is in app/dashboard/layout.js
function DashboardLayout({ children }) {
  const segment = useSelectedLayoutSegment()

  // If at /dashboard/settings
  // segment = 'settings'

  // If at /dashboard
  // segment = null

  return (
    <div>
      <nav>
        <span className={
          segment === 'settings'
            ? 'active'
            : ''
        }>
          Settings
        </span>
      </nav>
      {children}
    </div>
  )
}

Visual Example

graph LR A["/dashboard"] --> B["segment = null"] C["/dashboard/settings"] --> D["segment = 'settings'"] E["/dashboard/profile"] --> F["segment = 'profile'"] G["/dashboard/profile/edit"] --> H["segment = 'profile'"]

Key insight: It only tells you the immediate next part, not the full path!


🚀 redirect Function: “Teleport Me!”

The Story

Sometimes you need to instantly move someone to a different room:

  • Not logged in? → Go to login page!
  • Page not found? → Go to home!

⚠️ Important: Server-Side Only!

redirect works on the server - like a magical portal that moves you before you even see the page.

How It Works

import { redirect } from 'next/navigation'

// In a Server Component or Server Action
async function CheckAccess() {
  const user = await getUser()

  if (!user) {
    redirect('/login')
    // User teleports to /login
    // Nothing below this runs!
  }

  return <Dashboard user={user} />
}

Where Can You Use It?

graph LR A[redirect function] --> B[Server Components ✅] A --> C[Server Actions ✅] A --> D[Route Handlers ✅] A --> E[Client Components ❌]

Permanent vs Temporary

import { redirect, permanentRedirect } from 'next/navigation'

// Temporary redirect (307)
// "Visit this for now"
redirect('/new-page')

// Permanent redirect (308)
// "This page moved forever"
permanentRedirect('/new-home')

🌟 Real Example: Protected Page

import { redirect } from 'next/navigation'
import { cookies } from 'next/headers'

async function SecretPage() {
  const cookieStore = await cookies()
  const token = cookieStore.get('auth-token')

  if (!token) {
    redirect('/login')
  }

  return (
    <div>
      <h1>Secret Stuff! 🤫</h1>
    </div>
  )
}

export default SecretPage

🎪 Putting It All Together

Here’s how all these tools work as a team:

graph LR A[User visits /shop/toys?color=red] --> B[next/navigation toolbox] B --> C["usePathname#40;#41; → '/shop/toys'"] B --> D["useSearchParams#40;#41; → color='red'"] B --> E["useParams#40;#41; → { category: 'toys' }"] B --> F[useSelectedLayoutSegment in layout] F --> G["segment → 'toys'"] H[Need to move user?] --> I["redirect#40;'/somewhere'#41;"]

Complete Example

'use client'
import {
  usePathname,
  useSearchParams,
  useParams
} from 'next/navigation'

// File: app/shop/[category]/page.js
function ShopPage() {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const params = useParams()

  const color = searchParams.get('color')
  const category = params.category

  return (
    <div>
      <p>📍 Path: {pathname}</p>
      <p>📦 Category: {category}</p>
      <p>🎨 Color filter: {color || 'none'}</p>
    </div>
  )
}

Visit /shop/toys?color=blue and you’ll see:

  • 📍 Path: /shop/toys
  • 📦 Category: toys
  • 🎨 Color filter: blue

🎯 Quick Reference

Tool Question It Answers Returns
usePathname() Where am I? /shop/toys
useSearchParams() What filters are active? ?color=blue
useParams() What’s this page’s ID? { id: '123' }
useSelectedLayoutSegment() Which section am I in? 'settings'
redirect() Move user now! (no return)

🌈 You Did It!

You now have 5 superpowers for navigating Next.js apps:

  1. Know where you are with usePathname
  2. Read URL filters with useSearchParams
  3. Get dynamic IDs with useParams
  4. Track layout sections with useSelectedLayoutSegment
  5. Teleport users with redirect

These tools come from one magic box: next/navigation. Import what you need, and start building amazing navigation experiences! 🚀

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.