cacheLife
cacheLifeオプションにより、コンポーネントまたは関数内でcacheLife関数を使用する際、およびuse cacheディレクティブのスコープ内で、カスタムキャッシュプロファイルを定義できます。
使用方法
プロファイルを定義するには、cacheComponentsフラグを有効にし、next.config.jsファイルのcacheLifeオブジェクトにキャッシュプロファイルを追加します。例えば、blogプロファイルの場合:
next.config.ts
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
cacheLife: {
blog: {
stale: 3600, // 1時間
revalidate: 900, // 15分
expire: 86400, // 1日
},
},
}
export default nextConfigこのカスタムblog設定をコンポーネントまたは関数で以下のように使用できます:
app/actions.ts
TypeScript
import { cacheLife } from 'next/cache'
export async function getCachedData() {
'use cache'
cacheLife('blog')
const data = await fetch('/api/data')
return data
}リファレンス
設定オブジェクトには、以下の形式のキー値があります:
| プロパティ | 値 | 説明 | 要件 |
|---|---|---|---|
stale | number | サーバーをチェックせずにクライアントがキャッシュ値を保持する期間。 | オプション |
revalidate | number | サーバー上でキャッシュをリフレッシュする頻度。リバリデーション中に古い値が提供される場合があります。 | オプション |
expire | number | 値が動的に切り替わるまで古い状態を保持できる最大期間。 | オプション - revalidateより長くする必要があります |