Search code examples
reactjscachingreact-querytanstackreact-queryfetching-strategy

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


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.


Solution

  • 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