网页 综合 更新时间 2026-11-06 00:00:00

use cache

自动蜘蛛 nextjs.org 正文约 6000 字
use cache
The use cache directive allows you to mark a route, React component, or a function as cacheable. It can be used at the top of a file to indicate that all exports in the file should be cached, or inline at the top of a function or component to cache the return value. Functions and components that use use cache must be async.
use cache is a Cache Components feature. To enable it, add the cacheComponents option to your next.config.ts file:
Then, add use cache at the function, component, or file level. Cached functions and components must be async:
When used at file level, every exported function becomes a cached function and must also be async:
A cache entry's key is generated using a serialized version of its inputs, which includes:
When a cached function references variables from outer scopes, those variables are automatically captured and bound as arguments, making them part of the cache key.
In the snippet above, userId is captured from the outer scope and filter is passed as an argument, so both become part of the getData function's cache key. This means different user and filter combinations will have separate cache entries.
When a cached function reads root parameters, only the ones it actually reads become part of its cache key.
A cached function produces the same output for the same inputs. The first call with a given set of inputs runs the function body and stores its output. Every later call with the same inputs reuses that output, within a render pass and across requests, for as long as the entry lasts.
Outputs are stored by a cache handler, in memory by default, and last until they revalidate.
In the example above, each accountId has its own entry for getOrderSummary, holding the serialized { orders, totals } object it returns. Calls to getOrders have their own entries, keyed by the same accountId. If an earlier call, through the summary or directly, already filled one, db.orders.findMany doesn't run and those orders become part of the summary's output. See nested caching behavior for how an inner lifetime affects the entry around it.
Note that getOrderTotals is not cached. It is exported so other parts of the application can read fresh totals in an uncached scope. Inside getOrderSummary, though, the totals query only runs when that function runs following the 'hours' lifetime set there.
With Cache Components, prerendering fills the entry and keeps rendering, so this output contributes to the route's static shell and can contribute to its prefetch. A cache life too short to store safely leaves a hole that resolves at request time instead. See prerendering behavior for the thresholds.
Arguments to cached functions and their return values must be serializable.
For a complete reference, see:
Arguments and return values use different serialization systems. Server Component serialization (for arguments) is more restrictive than Client Component serialization (for return values). This means you can return JSX elements but cannot accept them as arguments unless using pass-through patterns.
You can accept non-serializable values as long as you don't introspect them. This enables composition patterns with children and Server Actions:
You can also pass Server Actions through cached components:
Cached functions execute in an isolated environment. The following constraints ensure cache behavior remains predictable and secure.
Cached functions and components cannot access runtime APIs like cookies(), headers(), or searchParams, and the restriction follows the call stack: a helper the cached function calls that reads one of these fails the same way, with the next-request-in-use-cache error. On a dynamically rendered route this surfaces when the route runs, so it can pass next build and fail under next start. Read these values outside the cached scope and pass them as arguments.
While use cache is designed primarily to include uncached data in the static shell, it can also cache data at runtime using in-memory LRU (Least Recently Used) storage.
With the default in-memory handler, runtime cache behavior depends on your hosting environment:
For example, in a serverless environment, a cached function shared by two pages executes on each static shell revalidation, whereas in self-hosted or environments with persistent memory, the cached output is reused if it's still fresh.
Hosting providers can replace the default cache handler, and some do not store use cache output at runtime. Values computed during prerendering are still reused by later requests, but values computed at request time are not. Check your hosting provider's documentation for its runtime caching behavior.
If the default in-memory cache isn't enough, or your provider does not store runtime output, consider use cache: remote which allows platforms to provide a dedicated cache handler (like Redis or KV database). This helps reduce hits against data sources not scaled to your total traffic, though it comes with costs (storage, network latency, platform fees).
With the default in-memory handler, serverless instances are ephemeral, so entries may not be reused between requests, unlike with use cache: remote. Neither caching directive carries over to a new deploy, because the cache key includes the build (or deploymentId) ID.
For data that needs to persist across deploys, use unstable_cache for non-fetch functions or the fetch cache.
Very rarely, for compliance requirements or when you can't refactor your code to pass runtime data as arguments to a use cache scope, you might need use cache: private.
When Draft Mode is enabled, all cached functions and components re-execute on every request, and results are not saved to the cache. This ensures draft content is always fresh without requiring any changes to your caching code.
You can read isEnabled from draftMode() inside a use cache scope, however, other runtime APIs like cookies() and headers() are not allowed, even when Draft Mode is active. See Passing runtime values to cached functions
访问原文 返回搜索 https://nextjs.org/docs/app/api-reference/directives/use-cache
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。