Sikau

Next.js · Day 4 · about 25 min

Linking and navigating

<Link>, useRouter and usePathname.

Instant page changes

A plain <a> reloads the whole site. Next.js's <Link> swaps just the page part, keeps layouts and their state, and even prefetches pages before you click — so navigation feels instant.

Link and navigation hooks

import Link from "next/link";

export const metadata = {
  title: { template: "%s · Himalayan Café", default: "Himalayan Café" },
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <nav>
          <Link href="/">Home</Link> · <Link href="/menu">Menu</Link> · <Link href="/about">About</Link>
        </nav>
        <main>{children}</main>
      </body>
    </html>
  );
}
  • In Client Components: const router = useRouter() from next/navigation gives router.push("/menu"), router.back() and router.refresh().
  • usePathname() returns the current path — great for highlighting the active link.
  • Links to other websites can stay plain <a> tags.

The rest of this lesson

  • Prefetching and soft navigationexplain
  • Navigating from codeexplain
  • What happens?predict
  • Which tool?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 19 lessons of Next.js