Capítulo 344 de 456

Linking and Navigating (Pages Router)

Core Idea

Client-side route transitions in the Pages Router go through the Link component (declarative) or the next/router API (imperative), both prefetching data for statically generated routes.

Key Concepts

  • Link: React component from next/link that performs client-side transitions between pages, similar to an SPA.
  • Automatic prefetching: any <Link /> in the viewport is prefetched by default (including data) for pages using Static Generation; server-rendered route data is fetched only on click.
  • URL object href: { pathname: '/blog/[slug]', query: { slug } } builds a path without manual string interpolation.
  • useRouter: recommended hook to access the router object inside function components.
  • withRouter: HOC alternative to useRouter for injecting the router into class components.
  • Shallow routing: router.push(url, as, { shallow: true }) updates the URL without re-running getServerSideProps/getStaticProps/getInitialProps.

Code Examples

import Link from 'next/link'

function Posts({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>
          <Link
            href={{
              pathname: '/blog/[slug]',
              query: { slug: post.slug },
            }}
          >
            {post.title}
          </Link>
        </li>
      ))}
    </ul>
  )
}
  • O que demonstra: navegação para rota dinâmica usando URL object em vez de interpolar a string manualmente.
import { useEffect } from 'react'
import { useRouter } from 'next/router'

// Current URL is '/'
function Page() {
  const router = useRouter()

  useEffect(() => {
    router.push('/?counter=10', undefined, { shallow: true })
  }, [])

  useEffect(() => {
    // The counter changed!
  }, [router.query.counter])
}
  • O que demonstra: shallow routing troca a URL/query sem recarregar dados nem desmontar a página.

Anti-patterns

  • Shallow routing entre páginas diferentes: shallow: true só funciona para mudanças de URL na página atual; navegar para outra página (/about) sempre descarrega a página atual e busca dados, mesmo pedindo shallow.
  • Confiar em shallow routing junto com proxy dinâmico: rewrites podem tornar a verificação client-side de "mesma página" não confiável; toda mudança de rota shallow deve ser tratada como tal.

Key Takeaways

  1. Link prefetcha automaticamente rotas com getStaticProps visíveis no viewport; rotas SSR só buscam dados ao clicar.
  2. Use useRouter (hooks) em vez de withRouter (HOC) como padrão recomendado.
  3. router.push(url, as, { shallow: true }) evita re-executar data fetching methods, útil para atualizar apenas query params.
  4. Shallow routing é limitado à página atual; não funciona ao trocar de rota.

Connects To

  • api-routes / getStaticProps: entender o que é (re)executado ou não durante navegação client-side.
  • use-router (API reference): detalhes completos do objeto router e withRouter.