Use cache directive
What you need to know
The use cache directive identifies a function or component whose result can be reused. It is a framework compilation feature, not a standard JavaScript memoization keyword.
By the end, you can: choose a cacheable public function; identify cache key dependencies.
Cache a public catalog query
import { cacheLife } from 'next/cache';type Category = 'nature' | 'travel';export async function titles(category: Category) { 'use cache'; cacheLife('hours'); return category === 'nature' ? ['Fern Atlas'] : ['River Walk'];}Expected behavior: nature and travel represent different public inputs; identical eligible calls can reuse output.
How it works
Choose results that are safe to share for a defined set of inputs. The documented key incorporates build and function identity, serialized arguments and captured serializable outer values. That makes explicit arguments a useful way to reveal dependencies to readers. At module scope the directive applies to supported exported async functions; at function scope it affects that function. Cached values must obey the framework serialization contract. React elements can be passed through in supported composition cases without inspecting them inside the scope. Non-serializable pass-through values do not participate in the cache key; do not use them to calculate cached output. Do not treat arbitrary objects, functions or request state as cache keys. Read request APIs outside ordinary use cache. A public category normalized to a small allowed domain is safe to pass; a session token is not. Cached execution may skip the function body, so never put a required audit, permission check or mutation inside it. React.cache has a different request-local role and is not a replacement for persistent cache configuration.
Normalize an untrusted public category before passing it
type Category = 'nature' | 'travel';function categoryFrom(raw: unknown): Category { return raw === 'travel' ? 'travel' : 'nature';}console.log(categoryFrom('travel'), categoryFrom('unknown'));Expected behavior: travel nature. The allowed domain bounds the number of category variants; this is pure TypeScript, not a framework cache test.
Common mistake
Passing user IDs or session cookies into a shared cache does not make authorization automatic. Never cache a required permission check or secret-bearing result as if it were public catalog data.
Practice and verification
List all dependencies of the titles function. Add a public language input only if it changes output; compare nature/en with nature/fr conceptually without storing arbitrary user-provided keys. Check cache hits in a future production fixture, not through console counts alone.
Scope: App Router, proposed Next.js 16.x and React 19, Cache Components enabled in a separate fixture. Framework snippets are staged and not executed; local pure models are not framework evidence. Exact patched dependencies and platform contracts are pending.