useQuery hook vs queryClient.fetchQuery, when to prefer one over the other

Viewed 1350

queryClient.fetchQuery can be used in place of useQuery hook provided by react-query. Any guidelines, best practices on in which scenario, one should be preferred over other.

One scenario might be where we want to conditionally fetch data. So, queryClient.fetchQuery looks more natural while useQuery hook not.

Is the above logic correct? Please advise on the best practise of using one over the other

1 Answers

fetchQuery is an imperative way to fetch data. You cannot call this during rendering, because it would be a side-effect and you cannot await the result. So you would need to spawn a useEffect.

The other difference is that useQuery creates a subscription to the queryKey, but fetchQuery does not. So if the data updates for some other reason (like a second component mounts and triggers a re-refetch of the query, or you refetch in the background because you focus the window and the query is stale), your component will not re-render and show the new data.

One scenario might be where we want to conditionally fetch data.

This is where you want the enabled option of useQuery, so that you can disable your query for as long as the conditions are not met.


The bottom line is: The two are not interchangeable, I have almost never used fetchQuery. For components, always useQuery

Related