The last chapter called updateTag("books") after adding a book and promised to explain what it was invalidating. This is that chapter. Caching is the part of Next.js that interviewers dig into hardest, partly because it's where real apps go wrong, and partly because it changed completely between versions. Next.js 14 cached almost everything by default and surprised people with stale pages. Next.js 15 turned the defaults off. Next.js 16 introduced Cache Components: nothing is cached unless you say so, and you say so with a directive, "use cache", right next to the code it caches.
You need both models. New apps (and every app created with create-next-app since 16.4) use Cache Components, and Next.js 17 will make it the default. Many codebases you'll join are still on the previous model. This chapter builds the core idea as a small simulation, then covers the real API in depth, the static shell it produces, and the older model with what 15 changed.
The problem: the same work on every request#
The reading list now has two kinds of data:
- The catalog: every book in the library, the same for every visitor. It changes a few times a day when an editor adds a book.
- My shelf: the signed-in user's own books. Different for everyone, read from a cookie-identified session.
Without caching, every request to /books queries the database for the catalog, even though ten thousand visitors in the last hour got the identical answer. That's wasted work, and worse, the page can't be prerendered and served from a CDN, because something on it needs a database round trip.
So you want to cache the catalog. Immediately you have to answer four questions, and they're the questions every cache answers:
- What's the key? Which inputs make two calls share a result?
- How long is it fresh? And what happens when it isn't: block the request, or serve the old value while refreshing?
- How do you invalidate it early? When an editor adds a book, the catalog is wrong now, not in an hour.
- Where does it live? One server's memory, a shared store, the CDN, the browser?
The shelf has the opposite problem: it must never be shared between users, but you'd still like the rest of the page around it to be fast.
Build it: a cache with lifetimes and tags#
Here's the idea behind "use cache", cacheLife and cacheTag as a small JavaScript cache. It's a simulation of the idea, not Next.js: one process, a fake clock you advance with buttons, and "background" regeneration done right after serving the stale value.
Each entry remembers its value, its tags and a lifetime profile with three numbers (in seconds), the same three Next.js uses:
revalidate: after this age, serve the cached value but regenerate it (stale-while-revalidate).expire: after this age, the value is too old to serve at all; the next read blocks and recomputes.stale: how long a browser may reuse it without asking the server. The simulation ignores this one; it's about the client cache, covered later.
Try this sequence: request the page twice (MISS, then HIT). Add a book to the database: the page still shows three books, because nobody told the cache. Then try each invalidation button and watch what the next two requests return.
import { useState } from "react";
import { createCache, createClock, profiles } from "./cache.js";
const clock = createClock();
const cache = createCache(clock);
const db = { books: ["Dune", "Emma", "Kindred"] };
const extra = ["Beloved", "Middlemarch", "Solaris", "Ubik"];
// Stands in for:
// async function getCatalog() {
// "use cache"; cacheLife("hours"); cacheTag("books");
// return db.book.findMany();
// }
function getCatalog() {
return cache.read("getCatalog()", () => [...db.books], { tags: ["books"], profile: profiles.hours });
}
const fmt = (s: number) => (s < 3600 ? `${s}s` : `${(s / 3600).toFixed(1)}h`);
export default function App() {
const [log, setLog] = useState<string[]>([]);
const add = (line: string) => setLog((l) => [`t=${fmt(clock.now())} ${line}`, ...l].slice(0, 14));
return (
<div style={{ fontFamily: "system-ui", fontSize: 14 }}>
<div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
<button onClick={() => {
const r = getCatalog();
add(`GET /books ${r.status.padEnd(5)} ${r.value.length} books: ${r.value.join(", ")}`);
}}>Request /books</button>
<button onClick={() => {
const title = extra[db.books.length - 3] ?? `Book ${db.books.length + 1}`;
db.books.push(title);
add(`DB write: added ${title} (cache not told)`);
}}>Add a book to the DB</button>
<button onClick={() => { cache.revalidateTag("books", "max"); add(`revalidateTag("books", "max")`); }}>revalidateTag max</button>
<button onClick={() => { cache.updateTag("books"); add(`updateTag("books")`); }}>updateTag</button>
<button onClick={() => { clock.advance(3600); add("...1 hour passes"); }}>Wait 1 hour</button>
<button onClick={() => { clock.advance(2 * 86400); add("...2 days pass"); }}>Wait 2 days</button>
</div>
<pre style={{ background: "#faf9f7", padding: 10, minHeight: 160 }}>{log.join("\n") || "Press Request /books"}</pre>
</div>
);
}What you just saw maps directly onto the real thing:
read(key, compute, options)is what"use cache"compiles your function into. The key is built from the function's identity and its arguments, so you never write one by hand.- The profile is
cacheLife.hourshere has the samerevalidateandexpireas Next.js'shourspreset. tagsiscacheTag.revalidateTag(tag, "max")gives you one STALE response and then fresh data.updateTag(tag)makes the very next request wait for fresh data. That difference is the whole reason both functions exist.- After two days with no traffic the entry was past
expire, so the request blocked (MISS) instead of serving a two-day-old catalog.
Cache Components: the real API#
Turn it on in next.config.ts. Apps created with create-next-app since 16.4 have Cache Components on already. The 16.4 release post describes the model as two flags: partialPrefetching (16.3) shipped separately but is now considered part of it, so set it explicitly too:
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
};
export default nextConfig;The first thing that changes is the default. With Cache Components, all dynamic code runs at request time unless you cache it. A fetch, a database query, a cookies() read: all fresh on every request. Caching is something you add, not something you discover.
"use cache" at three levels#
"use cache" Next.js 16 is a directive like "use client" and "use server". The compiler sees it and wraps the function so its return value is cached. Cached functions and components must be async.
import { cacheLife, cacheTag } from "next/cache";
import { db } from "./db";
export async function getCatalog() {
"use cache";
cacheLife("hours");
cacheTag("books");
const rows = await db.book.findMany({ orderBy: { title: "asc" } });
return rows.map((b) => ({ id: b.id, title: b.title, author: b.author, genre: b.genre }));
}Data-level caching (a function) is right when the same data feeds several components. UI-level caching (a component or page) also caches the rendered output, so the work of turning data into elements is skipped too. Both produce the same kind of entry: a serialized RSC payload, the format from Chapter 44.
What goes in the cache key#
You never write a key. Next.js builds it from:
- The build ID (or
deploymentIdif you set one). A new deploy starts with an empty cache. - A function ID: a secure hash of where the function lives and its signature.
- The serialized arguments: a component's props or a function's parameters.
- Captured variables: if a cached function closes over a variable from an outer scope, that value is bound as an argument and becomes part of the key.
- In development only, an HMR hash, so editing the file invalidates its entries.
async function Shelf({ userId }: { userId: string }) {
const getBooks = async (status: "reading" | "done") => {
"use cache";
// Key includes userId (captured) and status (argument).
return db.book.findMany({ where: { ownerId: userId, status } });
};
return <BookList books={await getBooks("reading")} />;
}That's why arguments and return values must be serializable, with two different rule sets. Arguments follow the rules for values sent to the server (primitives, plain objects, arrays, Dates, Maps, Sets, typed arrays), so class instances, functions and symbols can't be part of a key. Return values follow the rules for values sent to the client, so a cached component can return JSX.
There's one escape hatch: pass-through. A cached component can accept children (or other JSX slots, or a Server Action) as long as it doesn't look inside them. They're slotted into the output without becoming part of the key, which means a cached layout doesn't cache the page you pass it.
async function CachedFrame({ children }: { children: React.ReactNode }) {
"use cache";
cacheLife("days");
const nav = await getNavigation();
return (
<div>
<Nav items={nav} />
{children /* not cached, not in the key */}
</div>
);
}One more isolation rule surprises people: React's cache() has its own scope inside a "use cache" boundary. A value stored through cache() outside isn't visible inside. If a cached function needs something, pass it as an argument. That rule is what keeps the key honest: everything the function depends on is in its inputs.
cacheLife: three numbers#
cacheLife sets the entry's lifetime with the same three numbers as the simulation:
stale: how long the browser can reuse the result without asking the server. Sent to the client in thex-nextjs-stale-timeheader. The client router enforces a minimum of 30 seconds, so a prefetched link is still usable when the user clicks.revalidate: after this, the next request gets the cached value and triggers a background regeneration on the server.expire: after this with no requests, the next request waits for a fresh value. Must be longer thanrevalidate.
The presets:
| Profile | stale | revalidate | expire | For |
|---|---|---|---|---|
default (no cacheLife call) | 5 min | 15 min | never | |
seconds | 30 s | 1 s | 1 min | real-time data |
minutes | 5 min | 1 min | 1 hour | feeds, news |
hours | 5 min | 1 hour | 1 day | inventory, weather |
days | 5 min | 1 day | 1 week | blog posts |
weeks | 5 min | 1 week | 30 days | newsletters |
max | 5 min | 30 days | 1 year | legal pages, archives |
You can pass an inline object (cacheLife({ revalidate: 900 }); omitted fields inherit from default), define named profiles under cacheLife in next.config.ts, or even call cacheLife conditionally, as long as only one call runs per invocation. A common pattern: cacheLife("minutes") when a record isn't found yet, cacheLife("days") once it exists.
The docs recommend an explicit cacheLife in every "use cache" scope, and nesting is why. An outer cache with an explicit cacheLife keeps its own lifetime no matter what's inside. An outer cache without one uses default, but an inner cache with a shorter lifetime shortens it (a longer inner one can't lengthen it). And if the inner cache is short-lived enough to be excluded from prerendering, an outer cache with no explicit cacheLife is an error during prerendering, because its lifetime would silently collapse.
Short lifetimes also change where content can live:
revalidate: 0, orexpireunder 5 minutes: excluded from prerendering; it becomes a dynamic hole filled at request time. Of the presets, onlysecondsfalls here.staleunder 30 seconds: also excluded from prerendering.stalebetween 30 seconds and 5 minutes: prerendered, but left out of the route's App Shell (the reusable shell prefetched by default links).
cacheTag and on-demand invalidation#
cacheTag takes one or more strings (up to 128 tags, 256 characters each). Tag broadly and narrowly at once, so you can invalidate a list or a single record: cacheTag("books", "book-" + id). Tags can come from data you just fetched.
Four functions invalidate. Three appeared in the last chapter; here's the precise behavior:
revalidateTag(tag, profile): marks tagged entries stale. The next request is served the stale value and kicks off a regeneration. The profile says how long stale content may still be served; only itsexpireis read."max"(the recommended value) is a one-year window, so readers effectively always get an instant response.{ expire: 0 }means "never serve stale", which makes the next request block. Callable from Server Actions and Route Handlers. The one-argument form is deprecated and behaves like{ expire: 0 }.updateTag(tag)Next.js 16: expires tagged entries immediately. Server Actions only. It also makes Next.js re-render the current route and send the result in the action's response, and it clears the browser's prefetched routes. Built for read-your-own-writes.revalidatePath(path, type?): invalidates by route. Pass"page"or"layout"when the path contains a dynamic segment (revalidatePath("/books/[id]", "page")).revalidatePath("/", "layout")invalidates everything.refresh()Next.js 16: re-runs the uncached parts of the current route from a Server Action and leaves caches alone. Use it when a mutation changed uncached data, like a notification count.
A revalidation is triggered by requests, not by the call. Ten thousand pages tagged books aren't regenerated the moment you call revalidateTag; each regenerates when someone next visits it.
On the client, updateTag, revalidatePath and a revalidateTag whose profile resolves to expire: 0 clear the router's prefetched routes. revalidateTag(tag, "max") leaves the client cache alone. That's a trade-off you choose: "max" is cheaper and never blocks, and it means the user who made the change might not see it on this page right away.
Runtime data: cookies, headers, searchParams#
cookies(), headers() and searchParams describe one request. A shared cache entry can't depend on them, so calling them inside "use cache" throws (the next-request-in-use-cache error), and the rule follows the call stack: a helper that reads cookies() fails too when called from a cached function. On a dynamic route this only shows up when the route runs, so it can pass next build and fail under next start.
You have two patterns. The preferred one: read the runtime value outside, pass it in. The value becomes part of the key.
import { Suspense } from "react";
import { cookies } from "next/headers";
export default function BooksPage() {
return (
<>
<Catalog genre="all" />
<Suspense fallback={<p>Loading your shelf...</p>}>
<MyShelf />
</Suspense>
</>
);
}
async function MyShelf() {
const userId = (await cookies()).get("uid")?.value ?? "guest"; // runtime read, not cached
return <CachedShelf userId={userId} />;
}
async function CachedShelf({ userId }: { userId: string }) {
"use cache";
cacheLife("minutes");
cacheTag(`shelf-${userId}`);
const books = await db.book.findMany({ where: { ownerId: userId } });
return <ul>{books.map((b) => <li key={b.id}>{b.title}</li>)}</ul>;
}(A real app gets the user id from a verified session through the data access layer from Chapter 47, not straight from a cookie. The point here is where the runtime read happens.)
The second pattern, for when refactoring is impractical, is "use cache: private": a variant that may read cookies(), headers() and searchParams directly. Its results are never stored in a server cache across production requests; they're deduplicated within a request and kept in the browser for their stale time, which lets personalized content join a prefetch. You can't plug a custom cache handler into it.
And a third variant handles the opposite problem. By default, "use cache" entries created at request time live in an in-memory LRU per server instance. On a long-running Node server that's useful. On serverless, where each request may land on a fresh instance, runtime entries rarely get reused (build-time prerendered output is still reused normally). "use cache: remote" stores entries in a shared remote cache handler (Redis, a KV store, whatever your platform configures under cacheHandlers), at the cost of a network round trip per lookup.
"use cache" | "use cache: remote" | "use cache: private" | |
|---|---|---|---|
| Server-side storage | In memory per instance, or a cache handler | Shared remote handler | None across requests |
| Shared between users | Yes | Yes | No, per browser |
| Can read cookies or headers | No, pass values in | No, pass values in | Yes |
| Extra cost | None | Storage, network, lookup latency | None |
| Survives a deploy | No | No | Not applicable |
Reach for remote when the work is expensive or the upstream is slow or rate-limited, and the hit rate will be high. Skip it for work that's already fast (the docs suggest under about 50 ms), for keys that are mostly unique, or for data that changes every few seconds.
Uncached data must be in Suspense, or cached#
Here's the rule that makes the model work. With Cache Components, Next.js prerenders every route at build time and expects each component to do one of three things:
- Complete during prerendering: static markup, module imports, pure computation, synchronous file reads, and anything inside
"use cache"with a long enough lifetime. - Sit inside a
<Suspense>boundary if it awaits uncached data or reads runtime APIs. The fallback goes into the static output; the content streams at request time. - If neither, it's flagged. Development shows a blocking-route insight naming the component and offering the fixes: cache it, or wrap it in Suspense.
Non-deterministic values get the same treatment. Math.random(), Date.now() and crypto.randomUUID() during prerendering would freeze one value into the static output for everyone. Either cache it deliberately (everyone sees the same value until revalidation) or call await connection() from next/server first, inside a Suspense boundary, which says "this needs a real request":
import { connection } from "next/server";
async function RequestId() {
await connection(); // everything after this runs at request time
return <p>Request {crypto.randomUUID()}</p>;
}connection() replaced unstable_noStore() in Next.js 15. It's not allowed inside any "use cache" variant.
The static shell with dynamic holes#
Put those rules together and you get Partial Prerendering (PPR), which under Cache Components isn't a separate feature or flag anymore; it's simply what rendering does. At build time Next.js renders the route. Everything that completes, including cached components, becomes the static shell: HTML for direct visits plus an RSC payload for client navigations. Each Suspense boundary around request-time work leaves its fallback in the shell as a dynamic hole.
At request time the shell is sent immediately, often straight from a CDN without touching your server. The holes render on the server and stream into the same HTTP response. One URL, one response, part static and part dynamic.
The route has three parts: a static header, a book catalog marked 'use cache' with an hours lifetime, and a shelf that reads cookies(), wrapped in Suspense.
This is why params was a Promise back in the App Router chapter. A layout that awaits params at the top can't complete without the URL, so it drags everything below it out of the shell. A layout that passes the promise down and lets a small component await it inside a Suspense boundary keeps the layout, the sidebar and children in the shell. The docs' summary is good advice for any page: the deeper your async work sits in the tree, the more of the page can be prerendered.
When the route has dynamic params that weren't listed by generateStaticParams, the reusable version of the shell with param-specific parts behind fallbacks is the App Shell. Since 16.3 an unlisted URL serves the App Shell instantly on its first visit, renders the full page in the background, and caches it for the next visitor (Chapter 49 covers this ISR flow).
Where the cached copies live#
Each cached result is an RSC payload, and it can end up in three places, each governed by cacheLife:
- Prerendered output: the static shell's HTML and payload, on disk when self-hosting or in the platform's storage behind a CDN. Rebuilt per
revalidateandexpire. - The server cache: in-memory per instance by default, or a remote handler with
"use cache: remote". - The browser: included in navigation and prefetch responses and reused for its
staletime."use cache: private"results live only here.
All three are scoped to one deployment, since the build ID is in every key.
ensureStatic: guarding a static route#
Composition cuts both ways. One component that reads cookies() added to a shared header can quietly turn a fully static marketing page into request-time rendering, and you find out from your hosting bill. ensureStatic Next.js 16.4 is a route segment export that turns that into a build error:
export const ensureStatic = "navigation";
export default function BlogLayout({ children }: LayoutProps<"/blog">) {
return <article>{children}</article>;
}The values get stricter in order:
"shell": the App Shell that a default<Link>prefetches must be static (requires Partial Prefetching)."prefetch": the shell and per-link prefetches must be static."navigation": the whole server-rendered route must be static. Uncachedfetch,connection(),cookies(),headers(),searchParamsand short"use cache"lifetimes all fail the build.
"auto" (the default) and false are the other values. It works in pages and layouts, a child can only be stricter than its parent, and it requires Cache Components. Put "navigation" on the root layout of a marketing site and every page is guaranteed static.
The reading list, cached#
Here's the whole thing together. The catalog is shared and cached for hours; the shelf is per user; adding a book invalidates both with tags.
import "server-only";
import { cacheLife, cacheTag } from "next/cache";
import { db } from "./db";
export async function getCatalog() {
"use cache";
cacheLife("hours");
cacheTag("books");
return db.book.findMany({ select: { id: true, title: true, author: true } });
}
export async function getShelf(userId: string) {
"use cache";
cacheLife("minutes");
cacheTag(`shelf-${userId}`);
return db.shelf.findMany({ where: { userId }, select: { bookId: true, read: true } });
}The two invalidation calls show the trade-off in one app. The Server Action uses updateTag because the person who clicked Add must see their book now. The webhook uses revalidateTag(..., "max") because nobody is waiting, and serving stale for one more request is better than making a visitor wait.
The previous model: Next.js 14 and 15#
If cacheComponents isn't on (every app before 16, and many apps on 16), the older model applies. Its defining trait is that caching is implicit: decided by which APIs you call rather than declared. The Next.js 14 docs describe four layers:
| Layer | What | Where | Lifetime | Invalidate or opt out |
|---|---|---|---|---|
| Request memoization | Return values of fetch (GET) during one render | Server | One request | Not needed. Pass an AbortController signal to opt out. cache() for non-fetch |
| Data Cache | fetch responses, across requests and deployments | Server | Persistent | next: { revalidate: 3600 }, next: { tags } with revalidateTag, revalidatePath, or cache: "no-store" |
| Full Route Cache | Rendered HTML and RSC payload of static routes | Server | Persistent, cleared on deploy | Revalidating its data; dynamic = "force-dynamic" or revalidate = 0; using cookies(), headers() or searchParams |
| Router Cache | RSC payloads of visited and prefetched segments | Browser | Session; in 14, 30 s for dynamic and 5 min for static segments | router.refresh(), or revalidatePath/revalidateTag/cookies.set in a Server Action |
In Next.js 14 the defaults were "cache as much as possible": fetch was cached (force-cache), routes were static unless they used a dynamic API or uncached data, and GET Route Handlers were cached. One call to cookies() anywhere in the tree made the whole route dynamic, so a route was either static or dynamic, never both.
That produced the classic bugs: a page that never updates because a fetch deep in a helper was cached forever, a dashboard showing another moment's data because the Router Cache reused a segment, and nobody on the team able to say which layer was responsible.
Next.js 15 (October 2024) flipped the defaults without changing the architecture:
fetchis no longer cached by default. Opt in withcache: "force-cache". A route with no dynamic APIs is still prerendered, so itsfetchruns once at build; the difference shows on dynamic routes, whose fetches 14 served from the Data Cache and 15 sends upstream every time.- GET Route Handlers are no longer cached by default. Opt in with
export const dynamic = "force-static". - The client Router Cache no longer reuses page segments on navigation (
staleTimes.dynamicdefaults to 0). Back/forward navigation and shared layouts still reuse;loading.tsxis cached for 5 minutes.experimental.staleTimesrestores longer reuse. cookies(),headers(),draftMode(),paramsandsearchParamsbecame async, with a synchronous compatibility shim that Next.js 16 removed."use cache"appeared as an experimental feature behind a flag (dynamicIO, later renamedcacheComponents).
The previous model's tools, which you'll see in existing code:
// Per fetch
fetch(url, { cache: "force-cache" });
fetch(url, { next: { revalidate: 3600, tags: ["books"] } });
// Per route segment
export const revalidate = 3600; // a literal number; 60 * 60 isn't allowed
export const dynamic = "force-dynamic"; // or "auto" | "error" | "force-static"
export const fetchCache = "default-cache";
export const dynamicParams = false; // 404 for params not from generateStaticParams
// Non-fetch data
import { unstable_cache } from "next/cache";
const getBooks = unstable_cache(async () => db.book.findMany(), ["books"], { tags: ["books"], revalidate: 3600 });Moving between the two#
The mapping in the diagram is also the migration path:
unstable_cacheandfetchcaching options become"use cache"withcacheLifeandcacheTag.unstable_cacheLifeandunstable_cacheTaglost their prefix in 16.- Segment config
dynamic,revalidate,fetchCacheanddynamicParamsare not available with Cache Components. Their jobs are done by"use cache"lifetimes, Suspense boundaries, and (for unknown params)notFound()at request time. Theruntimeexport must go too. experimental.pprand theexperimental_pprroute export are gone; PPR is what Cache Components does.revalidateTag(tag)with one argument is deprecated in both models. UserevalidateTag(tag, "max")or, in Server Actions,updateTag(tag).- Turning on
cacheComponentsin an existing app surfaces build errors wherever uncached data sits outside Suspense. That's the migration's to-do list.
One caveat that matters for long-lived data: "use cache" entries don't survive a deploy. The previous model's Data Cache did. The docs point to unstable_cache or the fetch cache for data that must persist across deploys.
Pitfalls#
Check your understanding#
The toy cache from earlier, with its two invalidation functions removed. Implement them:
updateTag(tag): entries with the tag are gone; the next read is aMISSwith fresh data.revalidateTag(tag, profile):profileis a preset name ("max") or an object withexpire. Entries with the tag are marked stale: reads withinexpireseconds of the call get the old value once (STALE) and trigger a rebuild. After that window, reads block (MISS).{ expire: 0 }behaves likeupdateTag.
read already understands entries with staleSince and staleWindow set. Press Check when ready.
export const profiles = {
minutes: { stale: 300, revalidate: 60, expire: 3600 },
hours: { stale: 300, revalidate: 3600, expire: 86400 },
max: { stale: 300, revalidate: 2592000, expire: 31536000 },
};
export function createClock() {
let t = 0;
return { now: () => t, advance: (s) => { t += s; } };
}
export function createCache(clock) {
const entries = new Map();
function store(key, compute, tags, profile) {
const entry = { value: compute(), tags, profile, createdAt: clock.now(), staleSince: null, staleWindow: 0 };
entries.set(key, entry);
return entry;
}
function read(key, compute, { tags = [], profile = profiles.hours } = {}) {
const e = entries.get(key);
const now = clock.now();
if (e) {
const age = now - e.createdAt;
const marked = e.staleSince !== null;
const expired = age >= e.profile.expire || (marked && now - e.staleSince >= e.staleWindow);
if (!expired) {
if (age < e.profile.revalidate && !marked) return { value: e.value, status: "HIT" };
const old = e.value;
store(key, compute, tags, profile);
return { value: old, status: "STALE" };
}
}
return { value: store(key, compute, tags, profile).value, status: "MISS" };
}
function revalidateTag(tag, profile) {
// TODO
}
function updateTag(tag) {
// TODO
}
return { read, revalidateTag, updateTag };
}async function getBook(id: string) {
"use cache";
cacheLife("days");
return db.book.find(id);
}
async function BookCard({ id, compact }: { id: string; compact: boolean }) {
"use cache";
cacheLife("days");
const book = await getBook(id);
return compact ? <span>{book.title}</span> : <article>{book.title}: {book.summary}</article>;
}
export default function Page() {
return (
<>
<BookCard id="1" compact />
<BookCard id="1" compact={false} />
<BookCard id="2" compact />
<BookCard id="1" compact />
</>
);
}How many cache entries are created for BookCard, and how many for getBook?
async function Prices() {
"use cache";
cacheLife("minutes"); // revalidate 1 min, expire 1 hour
return <PriceTable rows={await getPrices()} />;
}
async function ProductPage() {
"use cache";
// no cacheLife here
return (
<>
<Description />
<Prices />
</>
);
}What lifetime does ProductPage's entry end up with? What changes if Prices uses cacheLife("seconds") instead? And if ProductPage adds cacheLife("days")?
A Server Action saves a book and calls revalidateTag('books', 'max'). The catalog component is cached with cacheTag('books'). What does the user see right after the action?
An interviewer asks: "How does caching work in Next.js 16 with Cache Components, and how is it different from the old model?"
"A Next.js 14 app's product page shows yesterday's prices even though the database is updated. How do you debug it, and how would Cache Components change the situation?"
Interview angle
With Cache Components in Next.js 16, everything is dynamic by default and you opt into caching with the "use cache" directive on an async function, component or file. The key comes from the build, the function's identity and its serialized arguments. cacheLife sets how long the browser may reuse it, when the server regenerates it in the background, and when it expires; cacheTag lets a Server Action expire it with updateTag or mark it stale with revalidateTag. Whatever completes at build time forms a static shell, and request-time parts stream into Suspense holes: partial prerendering. The old model cached implicitly in four layers, which 15 mostly turned off.
Explain the Cache Components model in Next.js 16.
What's the difference between updateTag and revalidateTag in Next.js 16?
Why can't you call cookies() inside "use cache", and what do you do instead?
What is the static shell, and how does partial prerendering work under Cache Components?
In the previous caching model (Next.js 14 and 15), what were the four layers, and how did you track down a stale page?
You deploy a Cache Components app to a serverless platform and runtime cache hits are near zero. Why, and what do you do?
Recap#
- Cache Components (
cacheComponents: true, default for new apps since 16.4) makes everything dynamic by default and caching explicit with"use cache"on async functions, components or files. - The key is the build ID, the function's identity and its serialized arguments, including captured variables. Runtime APIs can't be read inside; pass their values in, or use
"use cache: private"."use cache: remote"shares entries across instances. cacheLifesetsstale(browser, minimum 30 s),revalidate(background rebuild) andexpire(blocking rebuild).cacheTaglabels entries;updateTagexpires them for read-your-writes,revalidateTag(tag, "max")gives stale-while-revalidate,refresh()leaves caches alone.- Prerendering builds a static shell from everything that completes, with Suspense fallbacks as dynamic holes that stream at request time: that's PPR under Cache Components.
ensureStatic(16.4) fails the build if a route stops being static. - The previous model (14 and 15) caches implicitly in four layers: request memoization, Data Cache, Full Route Cache and Router Cache. Next.js 15 turned off caching for
fetch, GET Route Handlers and page segments in the Router Cache.
Sources#
- nextjs.org: Caching, use cache, use cache: private, use cache: remote
- nextjs.org: cacheLife, cacheTag, revalidateTag, updateTag, revalidatePath, refresh, connection
- nextjs.org: Route Segment Config, ensureStatic
- nextjs.org: Caching and Revalidating (Previous Model), Caching in Next.js 14, Upgrading to 15, Upgrading to 16
- nextjs.org blog: Next.js 15, Next.js 16, Next.js 16.4
- Facts checked November 24, 2026.