How to properly implement use cache with Next.js 16 App Router — replacing old implicit caching? #89375
|
Hi everyone 👋 What's the recommended pattern for using use cache alongside Server Components that fetch from external APIs? Should I place it at the layout level, page level, or individual component level? Any examples or migration tips would be really appreciated! |
Replies: 2 comments 3 replies
|
1. Where to place Place it as close to the data fetching as possible — ideally at the individual component or function level, not the layout. This gives you granular control. Example: async function ProductList() {
'use cache'
cacheLife('hours')
const data = await fetch('https://api.example.com/products')
return <List items={data.json()} />
}You can add it at the page or layout level, but that caches everything — which is rarely what you want with external APIs. 2. They work great together. PPR splits your page into a static shell and dynamic parts. Use export default async function Page() {
return (
<div>
<CachedProductList /> {/* use cache inside */}
<Suspense fallback={<p>Loading...</p>}>
<DynamicUserGreeting /> {/* runs at request time */}
</Suspense>
</div>
)
}3. Revalidation every few minutes: Use import { cacheLife } from 'next/cache'
async function getData() {
'use cache'
cacheLife({ stale: 60, revalidate: 300, expire: 3600 })
return fetch('https://api.example.com/data').then(r => r.json())
}ISR still works but 4. Turbopack + Turbopack builds are stable in Next.js 16. No known issues specifically with // next.config.ts
const nextConfig = {
cacheComponents: true,
}For self-hosted deployments, note that |
|
A few migration lessons from moving larger apps to Next.js 16:
For PPR, yes, it works well with Cache Components, but be careful around request-time APIs ( For data that updates every few minutes, I'd generally use: "use cache";
cacheLife("minutes");
cacheTag(...)rather than thinking in ISR terms. The cache model is much more explicit now. I ended up documenting the architecture, migration path from https://www.skills.sh/mohamed-hossam1/nextjs-cache-architecture/nextjs-cache-architecture Code examples: Might save you some migration pain. If it does, a ⭐ on the repo would be appreciated. |
1. Where to place
use cache:Place it as close to the data fetching as possible — ideally at the individual component or function level, not the layout. This gives you granular control. Example:
You can add it at the page or layout level, but that caches everything — which is rarely what you want with external APIs.
2.
use cache+ PPR:They work great together. PPR splits your page into a static shell and dynamic parts. Use
use cacheon the cacheable parts, and wrap truly dynamic parts (user-specific data) in<Suspense>. T…