unstable_cache()

Caches the result of an expensive async function in the Data Cache.

Since Next 14 Spec ↗

Syntax

const cached = unstable_cache(fn, keyParts?, options?)

Parameters

NameTypeRequiredDescription
fn (...args) => Promise<T> Yes The async function to memoize.
keyParts string[] No Extra cache key segments (when args do not fully identify input).
options { revalidate?: number | false, tags?: string[] } No Revalidation interval and cache tags.

Returns

(...args) => Promise<T> — A cached version of the function.

Examples

import { unstable_cache } from 'next/cache'

const getUser = unstable_cache(
  async (id: string) => db.users.findById(id),
  ['user'],
  { revalidate: 3600, tags: ['users'] }
)

export default async function Page({ params }) {
  const { id } = await params
  const user = await getUser(id)
  return <Profile user={user} />
}
// Invalidate via tag after a mutation
import { revalidateTag } from 'next/cache'
revalidateTag('users')

Notes

Use for non-`fetch` data (DB/ORM calls) you want in the Data Cache. Function arguments and `keyParts` form the cache key. Pair `tags` with `revalidateTag()` for on-demand invalidation. Still `unstable_`; `'use cache'` is the newer (canary) directive replacing it.

See also