Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Next.js の fetch 拡張とキャッシュ機構の違いを理解する

mattsu-
June 24, 2024

Next.js の fetch 拡張とキャッシュ機構の違いを理解する

Vercel Meetup #1 (2024/06/25) での発表資料
https://vercel.connpass.com/event/321176/

mattsu-

June 24, 2024
Tweet

More Decks by mattsu-

Other Decks in Technology

Transcript

  1. This Talk ・React と Next.js の fetch 拡張から Fetch Deduping

    と Data Cache の違いを 理解する ・React.cache や Next.js の unstable_cache の使 い方を知る 3
  2. React Removes `fetch` React 19 RC でネイティブの fetch Web API

    に 対する patch が削除された https://github.com/facebook/react/pull/28896 4
  3. Next.js implementation React `fetch` Next.js 15 RC では React の

    fetch 拡張を実装した 5 https://github.com/vercel/next.js/pull/65058
  4. fetch の拡張による Request Deduping async function hello() { // 実際に送信されるリクエストは1つだけ

    const res1 = await fetch("http://localhost/hello"); const res2 = await fetch("http://localhost/hello"); return {res1, res2}; } 8
  5. fetch の拡張による Request Deduping 9 async function Hello() { //

    実際送信されるリクエストは1つだけ const res1 = await fetch("http://localhost/hello"); const res2 = await fetch("http://localhost/hello"); return {res1, res2} } ・DB に直接アクセスしたい ・GraphQL や POST only な社内向け の API を利用している
  6. fetch の拡張による Request Deduping 10 async function Hello() { //

    実際送信されるリクエストは1つだけ const res1 = await fetch("http://localhost/hello"); const res2 = await fetch("http://localhost/hello"); return {res1, res2} } ・DB に直接アクセスしたい ・GraphQL や POST only な社内向け の API を利用している React.cache を使う
  7. React.cache による Request Deduping const getUser = cache(async (id) =>

    { return await db.user.query(id); }) async function Hello() { // DB へのリクエストは1回のみ const res1 = await getUser(1); const res2 = await getUser(1); }
 12
  8. Next.js の fetch 拡張による Data Cache ・組み込みの Data Cache を使用し、リクエストやデプロイ

    メントにまたがって結果を永続化する ・fetch のオプションでキャッシュの有効期間や再検証に使 用する Tag の設定ができる 16 // キャッシュを有効化する fetch(url, {cache: ‘force-cache’}) // 1分後に再検証する fetch(url, { next: { revalidate: 60 }})
  9. unstable_cache による Data Cache ・Data Cache を使用し、リクエストとデプロイメントにわ たって結果を保存する(fetch の拡張と同様) ・有効期間や再検証に使用する

    Tag を設定する const getCachedUser = unstable_cache( async (id) => getUser(id), // データ取得する非同期関数 ["my-app-user"], // データ識別用のキー { tags: ["my-app-user"] } // キャッシュの制御用のタグ ); 18
  10. まとめ ・React の fetch 拡張(現在は Next.js の実装) ・Request の重複排除(Request Deduping)を実現

    ・対応する機能は React.cache ・Next.js の fetch 拡張 ・Data Cache を利用してデータアクセスの効率化 ・対応する機能は unstable_cache 20