Skip to content
JL

Home

About

Blog

Contact

Shop

Portfolio

Privacy

TOS

Click to navigate

  1. Home
  2. Joshua R. Lehman's Blog
  3. Cache Components and use cache in Next.js

Table of contents

  • Share on X
  • Discuss on X

Related Articles

Revalidation and Cache Invalidation in Next.js
Next.js
12m
Nov 5, 2026

Revalidation and Cache Invalidation in Next.js

Cache invalidation becomes manageable when it is designed as a freshness contract: identify data ownership, tag cached reads, choose user-visible consistency, and prove mutations invalidate the intended surface.

#Next.js#Cache Invalidation+4
Server and Client Components in Next.js
Next.js
11m
Sep 24, 2026

Server and Client Components in Next.js

Server and Client Components are a design boundary, not a contest between two rendering styles. Learn what crosses the boundary, how imports affect bundles, and how to keep interactive islands focused.

#Next.js#Server Components+4
Data Fetching Composition in Next.js
Next.js
12m
Oct 22, 2026

Data Fetching Composition in Next.js

Fast Next.js data fetching is less about one cache flag and more about an honest dependency graph: parallel where possible, sequential where necessary, and streamed at the right boundary.

#Next.js#Data Fetching+4
Ask me anything! 💬

© Joshua R. Lehman

Full Stack Developer

Crafted with passion • Built with modern web technologies

2026 • All rights reserved

Contents

  • Caching Is a Product Boundary
  • Enable Cache Components Deliberately
  • Mark Reusable Work With use cache
  • Keep Request-Time Inputs Outside
  • Do Not Confuse Cache Lifetimes
  • Key Takeaways
Next.js

Cache Components and use cache in Next.js

October 29, 2026•6 min read
Joshua R. Lehman
Joshua R. Lehman
Author
Centred cache boundary diagram separating reusable content from request-time personalized data in Next.js
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:

  1. Can two visitors safely receive the same result?
  2. How stale may the result become before it is misleading or harmful?
  3. What event makes the result invalid?
  4. 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:

MechanismScopeWhat it solves
Request memoizationOne React renderDeduplicates matching work in a component tree.
React.cacheOne render/requestMemoizes arbitrary server functions such as ORM reads.
use cacheConfigured reusable cache scopeReuses 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:

  1. Request the same public data twice and confirm the expected reuse and invalidation.
  2. Request different locales, tenants, or consent states and confirm no result crosses a boundary.
  3. Update a source record and verify the intended cache-tag or time-based path exposes the new value.
  4. Simulate an upstream error and confirm an old response is not silently presented as fresh without the product’s intended policy.
  5. 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 cache scopes 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.