Zenn
Open2

use cache

ワッキーワッキー

従来の主なキャッシュ手法(もう必要なくなるかも?)

fetch
React cache
Next.js unstable.cache
Route Segment Config
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching#reference

fetch

Next.jsによって拡張されたfetchの第二引数にはキャッシュするためのオプションを入れられる

fetch(`https://...`, { cache: 'force-cache' | 'no-store' })

キャッシュさせたい場合は 'force-cache'
させたくない場合は 'no-store' とする

再検証させる頻度なども変えられる

fetch(`https://...`, { next: { revalidate: false | 0 | number } })

https://nextjs.org/docs/app/api-reference/functions/fetch#fetchurl-options

unstable_cache

fetchを使わないパターンでキャッシュさせる方法
第一引数にapiをリクエストするための関数を入れる
第二引数はタグ

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);
  ...
}

これで無理やりキャッシュさせられる
https://nextjs.org/docs/app/api-reference/functions/unstable_cache

Route Segment Config

セグメント単位でキャッシュさせたい場合

export const dynamic = 'auto'
// 'auto' | 'force-dynamic' | 'error' | 'force-static'

https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config

ログインするとコメントできます