Thuta Learning
Next.js
IntermediateWeb DevelopmentIntermediate

Linking and Fast Navigation

Next.jsLesson 725 min

What you'll walk away with

  • Choose <Link> for internal routes and a plain <a> for external links, downloads and mailto
  • Explain what re-renders and what stays during client-side navigation
  • Know why prefetching only happens in production builds
  • Decide the active link with usePathname, including the edge cases

Explain it simply

Explain it simply

If the whole browser reloads every time you move between pages of a site, the screen flashes white, the header is drawn again and all the JavaScript runs again, so the app feels slow. Next.js's Link avoids that and swaps only the part of the page that changes.

Link can also fetch what the next page needs before the user even clicks (prefetching), so the change feels almost instant. Shared layouts stay in place, so the sidebar and header do not flicker.

Problem → Why → Solution

The problem: internal navigation with <a> and window.location

The Myanmar Notes navigation bar is built from plain <a> tags, and an "Open" button changes window.location.href. A user types into the search box in the notes layout, opens a note, and the whole page reloads, wiping out what they typed. Users also complain that the screen flashes white every time they open a note.

components/notes-nav.tsx
"use client";

export function NotesNav() {
  return (
    <nav>
      <a href="/notes">All notes</a>  {/* full page reload */}
      <button onClick={() => (window.location.href = "/notes/routing")}>
        Open
      </button>                       {/* full reload, layout state lost */}
    </nav>
  );
}

Why does this happen?

Clicking an <a> and assigning window.location both make the browser request a whole new document. The entire React tree is thrown away and rebuilt, so all layout state is lost and the JavaScript has to start up again. <Link> intercepts the click and lets the Next.js router fetch only the segment that changed, so the document is never reloaded.

Core concept: client-side navigation and prefetching

<Link href="/notes"> renders as an ordinary <a href="/notes"> in the HTML. So the link still works before JavaScript arrives or when the user Ctrl+clicks to open a new tab, and search engines can follow it. Once JavaScript is running, Next.js intercepts a normal click and performs a client-side navigation: it updates the URL, adds a browser history entry, renders only the route segments that changed, and keeps the shared layouts. Back and forward work as usual, and by default the new page is scrolled to the top.

Prefetching means that when a link enters the viewport, the data its route needs is loaded in the background. It happens only in production builds, not under pnpm dev, which is one reason navigation can feel slower in development. How much is prefetched depends on whether the route is static or dynamic, and those details have changed between Next.js versions, so check the Linking and Navigating docs for your version. For pages with hundreds of rarely used links, prefetch={false} turns it off. To test prefetching yourself, run pnpm build and pnpm start, then watch the Network tab as you scroll links into view.

Link can be used directly in Server Components; it needs no "use client". Highlighting the active link requires knowing the current URL, so that part needs a small Client Component that calls usePathname from next/navigation. For navigating from code, for example after a form submits, use push, replace or back from useRouter(). For anything the user clicks, though, prefer <Link>: a useRouter call in onClick cannot be followed by crawlers or opened in a new tab.

Mental model: what happens on a Link click
  1. Link enters the viewport (prefetch)
  2. User clicks; Next.js intercepts
  3. Only changed segments render
  4. URL and history update, layouts stay

No new document is requested, so layout state survives and navigation is fast.

General pattern

tsx
import Link from "next/link";

<Link href="/path">Label</Link>
<Link href={`/items/${id}`} prefetch={false}>Label</Link>
<a href="https://other-site.com">External</a>

// In a Client Component only:
const pathname = usePathname();   // from "next/navigation"
const router = useRouter();       // router.push("/path")

Internal routes use <Link href>, with dynamic URLs built from template literals. Other sites use <a>. usePathname and useRouter come from next/navigation and only work inside Client Components.

Example: linking from the note list to detail pages

This page lists two notes and links each one to the /notes/[id] detail route. Notice that it uses no hooks, stays a Server Component, and still uses Link directly. The detail route itself is built in the dynamic routes lesson; for now, focus on how each href is formed.

tsx
import Link from "next/link";

const notes = [
  { id: "routing", title: "Learning routing" },
  { id: "server-components", title: "Server Components" },
];

export default function NotesPage() {
  return (
    <ul>
      {notes.map((note) => (
        <li key={note.id}>
          <Link href={`/notes/${note.id}`}>{note.title}</Link>
        </li>
      ))}
    </ul>
  );
}

Code breakdown

  1. Importimport Link from "next/link";

    Link is the default export of next/link. It works in Server Components, so no "use client" is needed.

  2. Data{ id: "routing", title: "Learning routing" },

    id goes into the URL, so it is written as a slug without spaces; title is the text the user sees.

  3. Key<li key={note.id}>

    key keeps the React list stable; the unique id is the natural choice.

  4. Dynamic href<Link href={`/notes/${note.id}`}>{note.title}</Link>

    The template literal produces two hrefs, /notes/routing and /notes/server-components. They appear in the HTML as <a href="/notes/routing">, and a click moves to the detail route without a reload.

You should see
Two note links appear, and clicking them takes you to the detail route without a full page reload.

Active links with usePathname

To highlight the current section in the navigation bar, write a small NavLink Client Component and use it from the layout, which stays a Server Component. aria-current="page" also tells screen reader users which page they are on. The "Notes" link should be active on /notes/routing, so the check matches a prefix, but "/" is only active on an exact match.

components/nav-link.tsx
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";

export function NavLink({ href, children }: { href: string; children: React.ReactNode }) {
  const pathname = usePathname();
  const active = href === "/" ? pathname === "/" : pathname.startsWith(href + "/")
    || pathname === href;

  return (
    <Link href={href} aria-current={active ? "page" : undefined}>
      {children}
    </Link>
  );
}

next/navigation, not next/router

In the App Router, useRouter, usePathname and useSearchParams are imported from next/navigation. next/router belongs to the Pages Router; using it inside app/ fails with an error saying the router was not mounted.

In real projects

In real projects

Documentation sites have hundreds of sidebar links and readers jump between pages quickly. With Link and prefetching, page changes feel instant, and the sidebar keeps its scroll position and expanded sections. In e-commerce, moving from a category page to a product page does not redraw the header with the cart icon, so client state such as the cart count animation carries on.

Where an action must finish before the user is sent on, such as a login form leading to the dashboard, use useRouter().push() or redirect() on the server, which the Server Actions lesson covers. Sending the user to another site, such as a payment provider, correctly uses a plain <a> or window.location, because your app's router does not handle other domains.

Common mistakes

Common mistakes

1. Using window.location for internal navigation

window.location.href = "/notes" reloads the whole page, losing layout state and the client cache. Use <Link> for anything the user clicks and useRouter().push("/notes") when navigating from code.

2. Using a Link without a real destination for an action

Writing an action that does not change the URL, such as "Delete", as a Link or <a> misleads keyboard and screen reader users, and Link requires an href anyway. Use a <button> for actions and Link for going to another page.

3. Checking the active link with a bare startsWith

pathname.startsWith("/notes") is also true on /notes-archive, and pathname.startsWith("/") is true everywhere, so the Home link is always active. Compare "/" exactly, and check other links against href + "/".

Best practices

Best practices

  • Keep the navigation bar in a Server Component layout and make only the small NavLink that needs active state a Client Component.
  • Mark the active link with aria-current="page", not just a colour.
  • Give links text that describes the destination page instead of "click here".
  • Reserve useRouter().push() for navigation the code decides on, such as after a form submits.

Mini challenge

Mini challenge: active navigation logic

Write the logic used inside NavLink as a separate function and test it against several pathnames. Print the nav bar as text with the active link wrapped in [ ].

  • Keep the three links, Home (/), Notes (/notes) and About (/about), in a typed array
  • isActive(pathname, href): "/" is active only on an exact match; others when equal to href or starting with href + "/"
  • renderNav(pathname) returns a string like "Home | [Notes] | About"
  • Test /, /notes, /notes/routing, /notes-archive and /about
nav-state.ts
type NavItem = {
  // TODO: href and label
};

const links: NavItem[] = [
  // TODO: Home, Notes, About
];

function isActive(pathname: string, href: string): boolean {
  // TODO: exact match for "/", prefix match (with a trailing "/") otherwise
}

function renderNav(pathname: string): string {
  // TODO: join the labels with " | ", wrapping the active one in [ ]
}

// TODO: print renderNav() for five pathnames, including /notes-archive

Expected: / -> [Home] | Notes | About /notes -> Home | [Notes] | About /notes/routing -> Home | [Notes] | About /notes-archive -> Home | Notes | About /about -> Home | Notes | [About]

Show hint

Use pathname === href || pathname.startsWith(href + "/") inside isActive. For "/" that rule would test for "//", which happens to keep Home inactive on /about, but write a separate if (href === "/") so the intent is clear.

Show solution
nav-state.ts
type NavItem = {
  href: string;
  label: string;
};

const links: NavItem[] = [
  { href: "/", label: "Home" },
  { href: "/notes", label: "Notes" },
  { href: "/about", label: "About" },
];

function isActive(pathname: string, href: string): boolean {
  if (href === "/") return pathname === "/";
  return pathname === href || pathname.startsWith(href + "/");
}

function renderNav(pathname: string): string {
  return links
    .map((link) => (isActive(pathname, link.href) ? `[${link.label}]` : link.label))
    .join(" | ");
}

for (const pathname of ["/", "/notes", "/notes/routing", "/notes-archive", "/about"]) {
  console.log(`${pathname} -> ${renderNav(pathname)}`);
}

Quick quiz 1 / 3

Where do you import useRouter from in an App Router Client Component?

Quick quiz 2 / 3

Running pnpm dev, you see no prefetch requests for links in the Network tab. Why?

Quick quiz 3 / 3

Which check keeps the Notes (/notes) link inactive when the pathname is "/notes-archive"?

What to remember

  • Link internal routes with <Link>: it renders an <a>, and Next.js turns clicks into client-side navigation.
  • Navigation renders only the segments that change and keeps shared layouts and their state.
  • Prefetching happens only in production builds, and its exact behaviour can differ between versions.
  • Use usePathname for active links and useRouter for navigating from code, both from next/navigation inside Client Components.

Next.js — Linking and Navigating — Next.js

Next.js — Linking and Navigating — Next.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Linking and Fast Navigation | Thuta Learning