unstable_cache

警告: 该 API 在稳定后将由 use cache 替代。

unstable_cache 允许您缓存昂贵操作(如数据库查询)的结果,并在多个请求间重复使用。

import { getUser } from './data';
import { unstable_cache } from 'next/cache';

const getCachedUser = unstable_cache(
  async (id) => getUser(id),
  ['my-app-user']
);

export default async function Component({ userID }) {
  const user = await getCachedUser(userID);
  ...
}

须知

  • 不支持在缓存作用域内访问动态数据源(如 headerscookies)。如果需要在缓存函数中使用这些数据,请在缓存函数外部使用 headers,并将所需的动态数据作为参数传入。
  • 此 API 使用 Next.js 内置的 数据缓存 (Data Cache) 来跨请求和部署持久化结果。

参数

const data = unstable_cache(fetchData, keyParts, options)()
  • fetchData:这是一个异步函数,用于获取您想要缓存的数据。它必须是一个返回 Promise 的函数。
  • keyParts:这是一个额外的键数组,用于进一步标识缓存。默认情况下,unstable_cache 已经使用参数和函数的字符串化版本作为缓存键。大多数情况下是可选的;只有在使用外部变量而不将它们作为参数传递时才需要使用它。然而,如果您不将它们作为参数传递,则必须添加函数内部使用的闭包。
  • options:这是一个控制缓存行为的对象。它可以包含以下属性:
    • tags:可用于控制缓存失效的标签数组。Next.js 不会使用此属性来唯一标识函数。
    • revalidate:缓存应重新验证的秒数。省略或传递 false 以无限期缓存,或直到调用匹配的 revalidateTag()revalidatePath() 方法。

返回值

unstable_cache 返回一个函数,当调用时,该函数返回一个解析为缓存数据的 Promise。如果数据不在缓存中,将调用提供的函数,其结果将被缓存并返回。

示例

import { unstable_cache } from 'next/cache'

export default async function Page({
  params,
}: {
  params: Promise<{ userId: string }>
}) {
  const { userId } = await params
  const getCachedUser = unstable_cache(
    async () => {
      return { id: userId }
    },
    [userId], // 将用户 ID 添加到缓存键
    {
      tags: ['users'],
      revalidate: 60,
    }
  )

  //...
}

版本历史

版本变更
v14.0.0引入 unstable_cache

On this page