Menu

Linking and Navigation

Lesson 3: Linking and Navigation

How do users move between pages?

Method Where it runs Use it for
<Link> from next/link Server or Client Components Normal links in the UI
useRouter() from next/navigation Client Components Navigating after an event, such as a button click
redirect() from next/navigation Server Components, Server Actions, Route Handlers Sending users elsewhere on the server, such as after login
permanentRedirect() Same as redirect URLs that have moved for good (308)
redirects in next.config.ts Before routing Large lists of old-URL to new-URL mappings

Example

// app/components/NavBar.tsx
'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';

const links = [
  { href: '/', label: 'Home' },
  { href: '/courses', label: 'Courses' },
  { href: '/about', label: 'About' },
];

export function NavBar() {
  const pathname = usePathname();
  return (
    <nav>
      {links.map((link) => (
        <Link
          key={link.href}
          href={link.href}
          className={pathname === link.href ? 'font-bold' : ''}
        >
          {link.label}
        </Link>
      ))}
    </nav>
  );
}

Navigating from code:

'use client';
import { useRouter } from 'next/navigation';

export function BackToCourses() {
  const router = useRouter();
  return <button onClick={() => router.push('/courses')}>Back to courses</button>;
}

How it works

  • <Link> renders a normal <a> tag, so it works for search engines and with JavaScript turned off.
  • When a link enters the viewport, Next.js prefetches the route in production so the click feels instant.
  • Navigation happens on the client. Shared layouts stay mounted; only changed segments load.
  • usePathname() reads the current URL path, which is useful for active link styles.
useRouter() method Effect
router.push(url) Navigate and add a history entry
router.replace(url) Navigate without a new history entry
router.back() Go to the previous page
router.refresh() Re-fetch Server Components for the current route

Common mistakes

Mistake Effect Fix
Using <a href> for internal links Full page reload, no prefetching Use <Link>
Importing useRouter from next/router Error in the App Router Import from next/navigation
Calling redirect() inside try/catch The redirect is caught as an error Call it outside the try block
Using router.push where a <Link> would do Loses accessibility and prefetching Prefer <Link> for anything a user clicks to go somewhere

Key takeaways

  • <Link> is the default way to navigate; it prefetches and keeps layouts mounted.
  • Use useRouter for navigation triggered by code, and redirect on the server.

Try it: Build the NavBar above and add it to the root layout so the current page's link is bold.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details