← All lessons
Lesson 04 · Beginner

Linking & Navigation

Move between pages without a full reload, and trigger navigation from code.

You can move between pages with a normal <a> tag, but that causes a full reload. The browser throws away your JavaScript state and starts over. Next.js gives you a special Link component that fetches the next page in the background and swaps the UI in place. It feels instant.

The Link component

import Link from "next/link";

export default function Nav() {
  return (
    <nav>
      <Link href="/">Home</Link>
      <Link href="/about">About</Link>
      <Link href="/blog/hello">Hello post</Link>
    </nav>
  );
}

By default, Next.js prefetches the page that a Link points to as soon as it appears on screen, so the click feels immediate.

Programmatic navigation

Sometimes you need to navigate from JavaScript — after a form submit, or based on user state. Use the useRouter hook (only available in client components):

"use client";

import { useRouter } from "next/navigation";

export default function LoginButton() {
  const router = useRouter();
  function handleClick() {
    // ...do something...
    router.push("/dashboard");
  }
  return <button onClick={handleClick}>Log in</button>;
}
  • **router.push(url)** — go to a new URL and add to history.
  • **router.replace(url)** — go without adding history (good after a redirect).
  • **router.back()** — go to the previous entry.
  • **router.refresh()** — refetch the current route's server data.

Knowing where you are

Use usePathname and useSearchParams (also from next/navigation) to read the current URL inside a client component. A common use is highlighting the active link:

"use client";

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

export default function NavLink({ href, children }) {
  const pathname = usePathname();
  const active = pathname === href;
  return (
    <Link href={href} style={{ fontWeight: active ? 700 : 400 }}>
      {children}
    </Link>
  );
}
Note: Import navigation hooks from next/navigation in the App Router. The older next/router is for the legacy pages router.

Try it

Convert this plain anchor tag to use Next.js client-side navigation.

Need a hint?

Import Link from next/link and replace the <a> element.

Quiz

Pick the best answer. You only get one shot per question.

1. Why use `<Link>` instead of `<a>` between Next.js pages?

2. Which import gives you access to `useRouter` in the App Router?

3. You want to navigate without adding a new entry to the browser history. Which method do you call?