0

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.

Mathis
  • 87
  • 1
  • 7

1 Answers1

1

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

TkDodo
  • 20,449
  • 3
  • 50
  • 65
  • 2
    With the example, it's clearer, thanks. I was missing the use case for prefetching on event, that is obviously not possible with a hook. – Mathis Jan 17 '23 at 14:23