Open12

tanstack queryに関するブログを読むその1

OsaOsa

I believe the React Query Defaults are very well-chosen, but they can catch you off guard from time to time, especially at the beginning.

well-chosenなんだ 👀

OsaOsa

First of all: React Query does not invoke the queryFn on every re-render, even with the default staleTime of zero. Your app can re-render for various reasons at any time, so fetching every time would be insane!

OsaOsa

Since React Query v5, refetchOnWindowFocus no longer listens to the focus event - the visibilitychange event is used exclusively. This means you'll get fewer unwanted re-fetches in development mode, while still retaining the trigger for most production cases. It also fixes a bunch of issues as shown here.

forcusイベントでre-fetchが減るのか 👀

OsaOsa

staleTime: The duration until a query transitions from fresh to stale. As long as the query is fresh, data will always be read from the cache only - no network request will happen! If the query is stale (which per default is: instantly), you will still get data from the cache, but a background refetch can happen under certain conditions.
staleTime: クエリが新しいものから古いものに移行するまでの期間。クエリが新しい限り、データは常にキャッシュからのみ読み取られ、ネットワーク リクエストは発生しません。クエリが古い場合 (デフォルトでは即時)、データはキャッシュから取得されますが、特定の条件下ではバックグラウンドの再取得が発生することがあります。

gcTime: The duration until inactive queries will be removed from the cache. This defaults to 5 minutes. Queries transition to the inactive state as soon as there are no observers registered, so when all components which use that query have unmounted.
gcTime: 非アクティブなクエリがキャッシュから削除されるまでの期間。デフォルトは 5 分です。クエリは、オブザーバーが登録されていないとすぐに非アクティブ状態に移行します。つまり、そのクエリを使用するすべてのコンポーネントがアンマウントされるとすぐに非アクティブ状態に移行します。

ほとんどの場合、これらの設定のいずれかを変更する場合、 staleTimeを調整する必要があります。 gcTimeを改ざんする必要はほとんどありませんでした。 ドキュメントにも例によるわかりやすい説明があります。

なるほど、変更するのは staleTimeか

stale と gcTime は↓がわかりやすそう
https://zenn.dev/taisei_13046/books/133e9995b6aadf/viewer/011a99

OsaOsa

I am referring to the dependency array of the useEffect hook here, which I assume you are familiar with.
Why are these two similar?

useEffectのdepsと同じようにqueryKeyを考えているのか

OsaOsa

情報に変更がない(コンポーネントのマウントごととか?)初期値の取得とかは便利なstaleTimeがあるよ

このデモの重要な部分は、React Query から取得した値をローカル状態に置かないことです。これにより、ローカルの「コピー」がないため、常に最新のデータが表示されるようになります。

OsaOsa

useQueryのenabledオプション

OsaOsa

queryCache ( queryClient.setQueryData) を改ざんする場合は、楽観的な更新、または変更後にバックエンドから受信したデータを書き込む場合にのみ使用してください。

以下2つのみとなるほど

  • 楽観的な更新
  • BEから受信したデータを書き込む