Linking with <Link>

Use the next/link component for fast, client-side navigation between routes.

Syntax<Link href="/path">Text</Link>

Navigate between pages with the <Link> component from next/link. It renders an anchor tag but performs client-side navigation β€” no full page reload β€” and automatically prefetches linked pages as they scroll into view, making transitions feel instant.

Why not a plain <a>?

A raw <a> triggers a full reload, discarding React state and refetching everything. <Link> keeps the app alive and only swaps the changed part of the tree.

Example

Example Β· typescript
import Link from 'next/link';

export default function Nav() {
  return (
    <nav>
      <Link href="/">Home</Link>
      <Link href="/blog">Blog</Link>
      <Link href={`/blog/hello-world`}>First post</Link>
    </nav>
  );
}

When to use it

  • A navigation bar uses Link components to move between pages without full browser reloads.
  • A blog index renders a list of post titles as Link elements pointing to /blog/[slug] routes.
  • A developer replaces anchor tags with Link to get automatic prefetching of linked pages when they enter the viewport.

More examples

Basic Link navigation

Link replaces anchor tags and handles client-side navigation with automatic prefetching.

Example Β· ts
import Link from 'next/link';

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

Link with dynamic segment

Template literals in the href build dynamic URLs for each item in a list.

Example Β· ts
import Link from 'next/link';

const posts = [{ slug: 'hello', title: 'Hello World' }];

export default function PostList() {
  return (
    <ul>
      {posts.map(p => (
        <li key={p.slug}>
          <Link href={`/blog/${p.slug}`}>{p.title}</Link>
        </li>
      ))}
    </ul>
  );
}

Active link with pathname

usePathname lets you compare the current URL to the link href to apply an active style.

Example Β· ts
'use client';
import Link from 'next/link';
import { usePathname } from 'next/navigation';

export default function NavLink({ href, label }: { href: string; label: string }) {
  const pathname = usePathname();
  return (
    <Link href={href} style={{ fontWeight: pathname === href ? 'bold' : 'normal' }}>
      {label}
    </Link>
  );
}

Discussion

  • Be the first to comment on this lesson.
Linking with <Link> β€” Next.js | SoundsCode