Why use QueryClient.prefetchQuery instead of useQuery for caching in react-query?

7.3k Views Asked by At

Why should I use QueryClient.prefetchQuery instead of useQuery for caching in React-Query?

I don't see any valuable use case. If I want to prefetch, I could just use useQuery when the app is loaded without actually using the fetched values. When I use it somewhere else, I would get the cached result from the previous useQuery. At least this is how I see things.

But I think I'm missing something. Maybe SSR related.

3

There are 3 best solutions below

1
On BEST ANSWER

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: https://tanstack.com/query/v4/docs/react/examples/react/prefetching

0
On

UseQuery 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.

0
On

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.