Capítulo 344 de 456
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.
Link: React component from next/link that performs client-side transitions between pages, similar to an SPA.<Link /> in the viewport is prefetched by default (including data) for pages using Static Generation; server-rendered route data is fetched only on click.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.router.push(url, as, { shallow: true }) updates the URL without re-running getServerSideProps/getStaticProps/getInitialProps.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>
)
}
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])
}
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.Link prefetcha automaticamente rotas com getStaticProps visíveis no viewport; rotas SSR só buscam dados ao clicar.useRouter (hooks) em vez de withRouter (HOC) como padrão recomendado.router.push(url, as, { shallow: true }) evita re-executar data fetching methods, útil para atualizar apenas query params.router e withRouter.