Why using QueryClient.prefetchQuery instead of useQuery for caching in react-query ?
I don't see any valable use case. If I want to prefetch, I just use useQuery at the load of the app without using returned values and when I will using it another time somewhere else, I will get the cache first. At least, this is how I see things.
But I think I'm missing something. Maybe SRR related.
3 Answers
Have you read the docs on prefecthing? It can be used to fetch something before you render it so that you can see the data instantly once the user navigates to it. If you wait until useQuery tries to read the data, you will inevitably fetch later and thus see a loading spinner.
We also use prefetching in one of our examples:
1UseQuery is used when the component is mounted or simply when it is destructured from a view.
const { queryProblem, queryComments } = useIssue();
queryClient.prefetchQuery is used before mounting a component, to make a request with arbitrary code apart from a condition or event.
For example, you could execute a prefetchQuery when the OnMouseEnter event fires.
A key difference between prefetchQuery and useQuery is that useQuery will re-execute (and so trigger a re-render) whenever the cache for its queryKey is invalidated, whereas prefetchQuery will not.
So if you have a mounted useQuery hook and you execute a mutation against its query key and use invalidateQueries, then the useQuery hook will re-render. However, the prefetchQuery would not re-render.
If you are literally just prefectching data then you do not want the fetch hook to repeatedly trigger a re-render later on whenever its cache is invalidated, and this is the use case for prefetchQuery.
So although prefetchQuery may seem to perform the same function as useQuery it should be the preferred option for prefetching.