'What are the difference between useInfiniteQuery vs QueryClientProvider usage in React Query?
So I've encountered a confusion on the preferable usage of QueryClientProvider
and useInfiniteQuery
. I've been using the useInfiniteQuery
function as a global state on some of the rendered components at the same time. Then I faced a problem where there is a component which has not been rendered yet to fetch the same data using the same useInfiniteQuery
. When the component is triggered to render, it will cause the useInfiniteQuery
to fetch again. I've solved this problem by giving an queryOptions
of enabled
set to false
, so the useInfiniteQuery
will not fetch automatically.
Sandbox Code (Note: You might want to set the Network into slow 3G, and try to use the enabled: false
query option).
Is this the preferred way to use React Query or is it better if I just use QueryClientProvider
? Are there any pros and cons regarding both of the options?
Solution 1:[1]
The recommended way is to always use the hooks in components, useQuery
or useInfiniteQuery
. Per default, stale queries will be refetched in the background when a component mounts that uses a query - you'll be instantly given the data though if it exists.
If you don't want background refetches, the best way is to set a staleTime
for your query. You can also turn off refetchOnMount
, but setting a staleTime
is preferred because it will tackle all sorts of background refetches (e.g. onWindowFocus). More here: https://tkdodo.eu/blog/react-query-as-a-state-manager
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | TkDodo |