Cache Components and use cache in Next.js


Caching is not a cosmetic performance knob. It is a decision to reuse an answer beyond the moment it was calculated. That decision affects freshness, personalization, data access, invalidation, costs, and how an application behaves when an upstream service is slow.
Cache Components make that decision more explicit in the App Router. With the feature enabled, uncached work happens at request time unless you mark a route, component, or function with use cache. The payoff is clarity: a reader can see which work is reusable and which must stay tied to the current request.
Caching Is a Product Boundary
Before writing a directive, answer four questions for a piece of data:
- Can two visitors safely receive the same result?
- How stale may the result become before it is misleading or harmful?
- What event makes the result invalid?
- Which request-time values—identity, locale, cookies, headers—change the answer?
Public catalog copy may be shared and refreshed every few minutes. A cart total, permission set, or account balance must not be reused as though it were public content. “It is expensive to calculate” is not enough reason to cache it; cache safety and freshness come first.
Explore data-reuse boundaries
Compare request memoization, explicit cache scopes, and request-time data. These lifetimes solve different problems.
Cache-scope explorer
Select a data-reuse boundary. This illustrates scope, not a live cache.
One React render / server request
Matching reads are deduplicated within the component tree, then the memoized value is discarded after rendering.
async function getProduct(id: string) {
'use cache';
return db.product.findUnique({ where: { id } });
}Enable Cache Components Deliberately
Cache Components are enabled with cacheComponents: true in next.config.ts:
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
cacheComponents: true,
};
export default nextConfig;The current Next.js configuration reference (opens in new tab) describes the feature as excluding App Router data-fetching operations from prerenders unless they are explicitly cached. In practice, this makes accidental caching harder and pushes the team to name reusable regions intentionally.
Adopt it route by route with measurement and tests. A change in caching model can expose hidden assumptions about static output, request-time APIs, or Suspense boundaries. Inventory important routes first: which data is public, user-specific, volatile, expensive, and operationally observable? Then set expectations for load behaviour before turning the flag into a broad migration.
Mark Reusable Work With use cache
Place use cache at the top of an async function, component, or file to establish the reusable scope:
export async function getProduct(id: string) {
"use cache";
return db.product.findUnique({ where: { id } });
}The directive says more than “put this in memory.” It makes the function’s arguments part of the cache key and defines a boundary where the framework can safely reason about reuse. Keep the scope small enough that its inputs and output are comprehensible. A getProduct(id) function is easier to audit than a full page that quietly depends on five globals.
The use cache reference (opens in new tab) permits the directive at route, component, and function levels. Function-level scopes are often a strong default because they turn a data contract into a visible unit: name, inputs, output, cache life, tags, and tests can live together.
Use cache configuration to express data semantics, not just load-test results. A marketing page can have a generous cache life; inventory and prices may need shorter revalidation and explicit tags; a rare expensive report might need a different strategy entirely. Next.js provides cacheLife and cacheTag alongside Cache Components for these choices, which the next article will cover in the context of invalidation.
Keep Request-Time Inputs Outside
Cookies, headers, and other request-time APIs are not accidental implementation details. They often represent identity, geography, feature access, or consent. Read them outside the cached scope and pass only the value that legitimately changes the cached result as an explicit argument.
import { cookies } from "next/headers";
export default async function ProductPage({ params }: PageProps) {
const { id } = await params;
const locale = (await cookies()).get("locale")?.value ?? "en-CA";
return <ProductDetails product={await getLocalizedProduct(id, locale)} />;
}
async function getLocalizedProduct(id: string, locale: string) {
"use cache";
return catalog.getProduct({ id, locale });
}This makes the input visible in the function signature and prevents a cache from silently blending requests that differ in a meaningful way. The official documentation specifically recommends reading cookies or headers outside cached scopes and passing values as arguments.
Do not pass a broad mutable request object into a cached helper to “make it work.” It obscures the cache key, makes review difficult, and can encourage accidental inclusion of sensitive state. Extract the smallest stable input, or keep the work request-bound if the answer is inherently personalized.
A Cached Scope Is Not a Permission Boundary
Authorization must happen before protected data enters a reusable scope. Never cache a query whose result depends on an unverified caller and assume the directive will keep tenants or users separate. Encode the verified scope in arguments—or keep the read request-time.
Do Not Confuse Cache Lifetimes
Three mechanisms can all look like “the data was reused,” but operate at different scopes:
| Mechanism | Scope | What it solves |
|---|---|---|
| Request memoization | One React render | Deduplicates matching work in a component tree. |
React.cache | One render/request | Memoizes arbitrary server functions such as ORM reads. |
use cache | Configured reusable cache scope | Reuses explicitly cacheable results across requests. |
Request memoization is useful even for uncached, fresh data. It prevents a layout and page from issuing the same matching read in one render. It does not make an answer durable for another visitor. Conversely, use cache is not a replacement for an intentional dependency graph or a local Suspense boundary.
Cache Components also isolate React.cache scopes. The current directive docs note that values stored through React.cache outside a use cache function are not visible inside it. This is a feature: cached units remain predictable and self-contained. Pass explicit arguments rather than using an in-memory cache as an invisible conduit between boundary types.
Test Freshness, Sharing, and Failure Modes
Test caching as behaviour, not just as a performance improvement:
- Request the same public data twice and confirm the expected reuse and invalidation.
- Request different locales, tenants, or consent states and confirm no result crosses a boundary.
- Update a source record and verify the intended cache-tag or time-based path exposes the new value.
- Simulate an upstream error and confirm an old response is not silently presented as fresh without the product’s intended policy.
- Trace cache hits, misses, render time, and data-source calls under production-like traffic.
The useful outcome is not the largest hit rate. It is a system where every cached result has a defensible sharing rule, lifetime, owner, and invalidation story.
Key Takeaways
- Cache Components make caching explicit: fresh work is request-time unless you mark a reusable boundary.
- Choose cacheability from sharing safety, freshness, invalidation, and request-time inputs—not cost alone.
- Keep
use cachescopes small and pass approved dynamic inputs as explicit arguments. - Never treat caching as authorization; verify access before protected data enters a reusable result.
- Distinguish per-request memoization from cross-request cached reuse, and test cache behaviour across real user boundaries.
Next, we will turn cache policy into dependable freshness with revalidation and invalidation: time-based lifetimes, tags, mutation-driven refreshes, and the observability needed to know a cache is actually correct.