Linking Between Pages
Trailhead now has three pages, and the header needs links between them. A plain <a href="/trails"> works, but every click throws the whole page away and loads it again: the header flickers, the scroll resets, and anything the hiker typed is lost. Next.js has a better door.
The rule
Linkfor clicks,router.pushfor code; a plain<a>reloads everything.
The Link component from next/link renders a normal <a> tag, so it is accessible and works with "open in new tab". But when clicked, Next.js intercepts it and swaps in the new page inside the browser, keeping the parts that did not change.
// app/layout.tsx (part of the header)
import Link from "next/link";
<nav>
<Link href="/">Home</Link>
<Link href="/trails">Trails</Link>
<Link href="/about">About</Link>
</nav>Link also prefetches: in a production build, when a link scrolls into view, Next.js quietly loads what that page needs in the background, so the click feels instant.
Sometimes navigation comes from code rather than a click, such as after a search form is submitted. For that, use the useRouter hook from next/navigation. Hooks run in the browser, so the component needs "use client" at the top of its file (a later lesson explains this line).
"use client";
import { useRouter } from "next/navigation";
export function TrailSearch() {
const router = useRouter();
function onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const q = new FormData(e.currentTarget).get("q");
router.push(`/trails?q=${encodeURIComponent(String(q))}`);
}
return <form onSubmit={onSubmit}><input name="q" /></form>;
}Useful router methods: push (go, adding a history entry), replace (go, replacing the current entry), back, and refresh (fetch the current page's server content again).
The shortcut
Ask "Is the visitor clicking something that goes somewhere?" Yes: Link. No, my code decides after an event: router.push. An external site: a plain <a> is fine, because there is nothing of yours to keep.
Header links
Visitors click them to go to a page:
Link.
The trap is importing useRouter from next/router. That is the older Pages Router version. In the App Router it comes from next/navigation.
Drills
Answer fast — trust the rule.
What does a plain <a href="/about"> do when clicked inside a Next.js app?
Where do you import useRouter from in the App Router?
After a hiker signs out, your code should send them to / without leaving the old page in history. Which call fits?
Why does navigation with Link often feel instant in production?
Remember
Linkfor clicks,router.pushfor code-driven navigation; a plain<a>reloads everything.- Shortcut: clicking to go somewhere means
Link; external sites can use<a>. - Trap:
useRoutercomes fromnext/navigationin the App Router, notnext/router.
