Capítulo 65 de 456
With Cache Components and Partial Prefetching, <Link> prefetches one shared App Shell per route by default. Use prefetch={true} per link to also resolve URL-specific data (searchParams, params) ahead of navigation, and "use cache" / "use cache: private" to include session data in the shell.
cookies()/headers()); shared across all links to that route.prefetch={true}: resolves a link's URL data (searchParams/params) at prefetch time, on top of the App Shell; costs one server invocation per prefetchable link.prefetch={false} / default: only the App Shell is prefetched; URL-specific content streams in after navigation.partialPrefetching: config flag (requires Cache Components) that enables the App Shell prefetch model.cookies()/headers() outside a "use cache" function and pass the value as an argument, so the cache entry is keyed on that value and shared across sessions with the same value."use cache: private": assigns a cache lifetime to a function that reads runtime request data (cookies/headers) directly inside it; results cached per-browser/session only.import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
export default function SearchPage({ searchParams }: PageProps<'/search'>) {
return (
<>
<h1>Search</h1>
<Suspense fallback={<ResultsSkeleton />}>
<Results searchParams={searchParams} />
</Suspense>
</>
)
}
async function search(q: string) {
'use cache'
return db.search(q)
}
<Link prefetch={true}> para /search?q=react resolve q no prefetch e reaproveita o cache de search(q), eliminando o fallback no clique.async function getUser() {
'use cache: private'
const session = (await cookies()).get('session')?.value
return db.users.findBySession(session)
}
cookies() para fora da função cacheada.| App Shell | Per-link prefetch (prefetch={true}) | |
|---|---|---|
| Scope | Um por rota | Um por <Link prefetch={true}> visível |
| Content | Saída renderizada da rota menos dado por link | O mesmo, mais dado de URL resolvido |
| Cost | Limitado pelo número de rotas | Limitado pelo número de links visíveis |
| Role | Prefetch padrão | Mais conteúdo pronto antes do clique |
prefetch={true} em grade de muitos cards: cada link visível dispara uma invocação de servidor; prefira prefetch por hover (intent) nesse caso.prefetch={true} quando o conteúdo precisa ser sempre fresco: o prerender para no mesmo fallback de <Suspense>, então não há ganho.prefetch={true} só ajuda em rotas cuja árvore depende de dados de URL com um lifetime de cache definido ("use cache"/"use cache: private")."use cache: private" (por sessão).params também precisa de <Suspense>, mesmo quando previsto por generateStaticParams.prefetch prop, router.prefetch).