Capítulo 368 de 456

Link

Core Idea

<Link> (Pages Router) extends <a> to provide prefetching and client-side navigation; it's the primary way to move between routes.

Key Concepts

  • href (required): path or URL object ({ pathname, query }) to navigate to.
  • replace: default false; when true, replaces history entry instead of pushing.
  • scroll: default true; scrolls to top of the target Page unless false.
  • prefetch: default true, prefetches route+data on viewport enter (production only); false prefetches only on hover.
  • shallow: updates the URL without rerunning getStaticProps/getServerSideProps/getInitialProps.
  • locale: overrides or disables (false) automatic locale prepending.
  • onNavigate: event handler fired only on client-side SPA navigation (not on modifier-key clicks, external URLs, or download links); receives an event with preventDefault().
  • as: legacy decorator for the displayed URL (pre-9.5.3 dynamic routes pattern), still used with Proxy rewrites.

Code Examples

import Link from 'next/link'

export default function Home() {
  return <Link href="/dashboard">Dashboard</Link>
}
  • O que demonstra: basic navigation usage.
<Link
  href="/dashboard"
  onNavigate={(e) => {
    console.log('Navigating...')
    // e.preventDefault()
  }}
>
  Dashboard
</Link>
  • O que demonstra: intercepting client-side navigation via onNavigate.

Reference Tables

PropTypeRequired
hrefString or ObjectYes
asString or Object-
replaceBoolean-
scrollBoolean-
prefetchBoolean-
shallowBoolean-
localeString or Boolean-
onNavigateFunction-

Anti-patterns

  • Relying on onClick for navigation-only logic: fires on every click (including modifier-key clicks and downloads); use onNavigate when the intent is specifically SPA navigation.
  • Prefetching through a Proxy rewrite without as: Next.js can't resolve the correct route to prefetch; pass both the display href and the actual rewritten path.

Key Takeaways

  1. Prefetching only happens in production and only for prefetch !== false.
  2. scroll={false} disables the scroll-to-top/hash behavior; use CSS scroll-padding-top for sticky headers instead.
  3. shallow skips data-fetching functions, useful for URL-only updates (e.g. filters).
  4. Use onNavigate, not onClick, to hook specifically into SPA transitions.

Connects To

  • Proxy: rewrites interact with Link's prefetching via the as/href split.
  • useRouter: shallow routing and imperative navigation counterpart to <Link>.