Composable Caching with Next.js
Key Points
- Compiler-derived cache keys include closure dependencies
- Non-serializable values become runtime references
- Supports tagging and targeted invalidation
Summary
'use cache' is a compiler directive in Next.js that marks functions or components as cacheable. The Next.js compiler statically analyzes closures to produce reliable cache keys (including captured values), serializes supported inputs via React serialization, and represents non-serializable inputs as runtime references so inner dynamic children or complex objects do not invalidate cached outputs. The feature supports tagging, custom cacheLife() profiles, and targeted invalidation via cacheTag() / revalidateTag(). It is experimental.
Key Points
- Compiler-driven cache keys: the directive lets the compiler include closure dependencies automatically, avoiding manual key mistakes common with runtime
cache()functions. - Serializable vs non-serializable: serializable arguments are used in the cache key; non-serializable values become runtime references that are restored when the cached result is deserialized.
- Composable (donut) caching: children can remain dynamic references so updating child components doesn't invalidate the outer cached result.
- Tagging & invalidation: use
cacheTag()to tag entries,revalidateTag()to invalidate, andcacheLife()to set cache profiles (defaults provided, custom allowed). - Practical guidance: prefer
"'use cache'"for local, safe caching; ensure deterministic serializable inputs for keys; tag after fetching when you want targeted revalidation. - Status: experimental — test and provide feedback; consult the docs for exact API and migration notes.