Cache Components and use cache
Opt in to caching with the use cache directive and cacheLife, mix static, cached and streamed content on one page, and learn what a cached function cannot read.
Cache Components and use cache
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- With cacheComponents enabled, data fetching is dynamic by default and you choose what to cache by adding the use cache directive to a function, component, or file.
- Every page is prerendered into a static shell made of three kinds of content: things that finish at build time, cached results, and Suspense fallbacks for content that streams at request time.
- Pair every use cache with a cacheLife; the built-in profiles are seconds, minutes, hours, days, weeks, and max.
- A cached scope cannot read cookies(), headers(), or searchParams; read them outside and pass the values in as arguments, which also become part of the cache key.
- Short-lived caches, such as the seconds profile or an expire under five minutes, are excluded from the prerender and become request-time holes.
From implicit to explicit
The earlier model cached too much without being asked, so people spent their time finding out what had been cached. Cache Components flips it. Data fetching is dynamic by default, and you say what to cache.
In Next.js 16.4, a project from create-next-app already has this turned on. To enable it by hand:
// next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
The docs ask you to set partialPrefetching explicitly: leaving it unset logs a warning.
The use cache directive
use cache marks an async function, component, or whole file as cacheable. The first call with a set of inputs runs the body and stores the result; later calls with the same inputs reuse it.
// lib/data.ts
import { cacheLife, cacheTag } from 'next/cache'
export async function getPosts() {
'use cache'
cacheLife('hours')
cacheTag('posts')
return db.query('SELECT * FROM posts')
}
You can cache at the data level (as above) or cache a component or page that renders the data. The docs recommend pairing every use cache with a cacheLife; without one, the default profile applies.
| Profile | stale | revalidate | expire |
|---|---|---|---|
seconds |
30s | 1s | 60s |
minutes |
5m | 1m | 1h |
hours |
5m | 1h | 1d |
days |
5m | 1d | 1w |
weeks |
5m | 1w | 30d |
max |
5m | 30d | 1y |
stale is how long the browser may reuse it, revalidate is when the server regenerates in the background, and expire is when it must be recomputed before serving. You can pass your own object instead of a profile name.
Three kinds of content on one page
A page prerenders at build time into a static shell, and every piece of it falls into one of three bins:
- Finishes at build time. Imports and pure computation. They go into the shell.
- Cached with
use cache. The cached result goes into the shell. - Needs the request. Wrap it in
<Suspense>. The fallback goes into the shell, and the content streams in.
Here is a page from my 16.4.6 test project that uses all three:
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { getPosts } from '@/lib/data'
export default function Page() {
return (
<>
<h1>Posts</h1>
<Posts />
<Suspense fallback={<p>loading</p>}>
<Theme />
</Suspense>
</>
)
}
async function Posts() {
const posts = await getPosts() // cached
return <ul>{posts.map((p) => <li key={p.slug}>{p.title}</li>)}</ul>
}
async function Theme() {
const theme = (await cookies()).get('theme')?.value ?? 'light' // per request
return <p>{theme}</p>
}
next build printed the route as ◐ /ok with a revalidate of 1h and an expire of 1d. The legend: “◐ (Partial Prerender) prerendered as static HTML with dynamic server-streamed content”. The heading and the cached list are static; only Theme waits for a request.
Remove the <Suspense> around Theme and the same build fails with the blocking-route error, as the earlier lesson showed.
What a cached function cannot read
The cache is shared. A result computed for one visitor could be served to another, so a cached scope cannot call cookies(), headers(), or read searchParams. I put cookies() inside a use cache component and next build failed with: “cookies() can’t be read inside “use cache”. Read it outside the cached function and pass what you need as an argument.”
Do that. Read at the edge, pass the value down:
async function Profile() {
const session = (await cookies()).get('session')?.value
return <CachedContent sessionId={session} />
}
async function CachedContent({ sessionId }: { sessionId?: string }) {
'use cache'
const data = await fetchUserData(sessionId) // sessionId is part of the key
return <div>{data}</div>
}
Arguments and captured variables become the cache key, so different sessions get different entries. Arguments must be serializable: plain objects, arrays, primitives, dates; class instances and functions are not allowed (functions and JSX only as pass-through values you do not inspect).
Where entries live
Cache entries use an in-memory handler by default. The docs are clear about the consequence: on a long-running server, entries persist across requests; on serverless hosting, entries typically do not, though values computed during prerendering are still reused. For durable shared storage there is use cache: remote, which needs a platform cache handler. Entries also do not survive a deploy, because the build id is part of the key.
What the video covers
Ankita Kulkarni’s video was made for the Next.js 16 release. By its chapters: it shows a demo with no caching, enabling Cache Components, the use cache directive, partial pre-rendering, mixing static and dynamic, improving UX with skeletons, cacheLife for revalidation, revalidateTag for purging, caching an entire component, and custom cache profiles. It also touches Core Web Vitals and skeletons, which are outside this lesson. Two runner-up videos are linked: Web Dev Simplified’s was made on the March 2025 canary, when this was the dynamicIO flag, so the idea matches but names differ.
Where this fits
Caching makes reads fast; the next question is how to make a cached read fresh again after the data changes. Next: revalidation and cache tags.
Check yourself
Where do you add use cache, and what must the function or component be?
At the top of an async function or component body, or at the top of a file to cache every export, and the function must be async.
What happens if you read cookies() inside a use cache function?
It fails with the next-request-in-use-cache error, because the result would be shared across requests, so you read the cookie outside the cached scope and pass the value in as an argument.
Why does the cacheLife seconds profile not appear in the static shell?
Its expire of one minute is under the five-minute threshold, so it is treated as short-lived and excluded from prerenders, leaving a hole that resolves at request time.
What forms a cache key for a use cache function?
The build ID, a hash of the function's location and signature, and its serializable arguments, plus any values captured from the enclosing scope.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.