Tech Hotoke Blog

IT観音とは私のことです。

#ReactQuery フェッチタイミングの制御Tips #invalidateQueries #resetQueries

これは何?

ReactQueryのフェッチタイミングの制御とかを触った。毎回調べている感じがするので、メモ。

前提

  • React: 18系
  • TypeScript: 4系
  • TanStack Query: 4系

Tips

  const { data } = usePlaylistAutoProgram(playlist?.playlistUid)

 useEffect(() => {
    if (data) {
      setValue('hoge', data.hoge)
    }
  }, [data])

  const onSubmitForm: SubmitHandler<FormInputs> = async (
    values
  ) => {
    await updatePlaylistAutoProgram({
      data: values
    })
    // 更新したデータでfieldの値を更新したい。 
  }
 const queryClient = useQueryClient()
  const { data } = usePlaylistAutoProgram(playlist?.playlistUid)

 useEffect(() => {
    if (data) {
      setValue('hoge', data.hoge)
    }
  }, [data])

  const onSubmitForm: SubmitHandler<FormInputs> = async (
    values
  ) => {
    await updatePlaylistAutoProgram({
      data: values
    })
    // 
    queryClient.resetQueries([
      '<任意のキー>',
      [任意のバリュー]
    ])
  }
  • ReactQueryはdefaultで5分間キャッシュされる。
  • キャシュしないか明示的にリフェッチするかは要件次第だと思いますが、今回は特定の用途でしかリフェッチする必要がないため、キャッシュ設定はそのままに明示的にリフェッチするようにしました。

useQuery | TanStack Query Docs

補足

  • キャッシュ時間を0にするには?
    • chacheTimeを0にする + retryフラグをfalseにする。(記憶ベースで恐縮なんですが、chacheTimeを0にするだけではキャッシュが無効にならず、GitHubリポジトリに同様の投稿があり、retryフラグをfalseにすれば治りました)
 cacheTime: 0,
 retry: false
  • resetQueriesinvalidateQueries の 使い分け
    • 今回実装するにあたって、どちらが適切か判断ができず、違いがよくわかっていなかったので改めてドキュメントを読んでみました。

    • resetQueriesは、指定したクエリをキャッシュから完全に削除し、初期状態に戻す。アクティブなクエリは自動的にリフェッチされる。

    • invalidateQueriesは、指定したクエリをキャッシュから無効化する。完全に削除はしません。アクティブなクエリが自動的に再フェッチされるかどうかは設定次第。

    • 上記を踏まえると、それぞれの使用例はこんな感じなのかなぁ。。。

      • resetQueriesの使用例

        • フォームの入力内容をリセットした際に、関連するクエリも初期状態に戻したい場合
        • アプリの設定を変更した際に、関連するクエリをすべて再フェッチしたい場合
      • invalidateQueriesの使用例

        • リストの一部分を更新した際に、そのリストに関連するクエリだけを無効化してリフェッチしたい場合
        • データを更新した際に、そのデータを使用しているクエリを無効化して、次回アクセス時にリフェッチさせたい場合

QueryClient | TanStack Query Docs

The resetQueries method can be used to reset queries in the cache to their initial state based on their query keys or any other functionally accessible property/state of the query. This will notify subscribers — unlike clear, which removes all subscribers — and reset the query to its pre-loaded state — unlike invalidateQueries. If a query has initialData, the query's data will be reset to that. If a query is active, it will be refetched.

QueryClient | TanStack Query Docs

The invalidateQueries method can be used to invalidate and refetch single or multiple queries in the cache based on their query keys or any other functionally accessible property/state of the query. By default, all matching queries are immediately marked as invalid and active queries are refetched in the background. If you do not want active queries to refetch, and simply be marked as invalid, you can use the refetchType: 'none' option. If you want inactive queries to refetch as well, use the refetchType: 'all' option