PavitraK
PavitraK

Reputation: 1

Why data doesn't re-fetch when staleTime set to Infinity and cacheTime set to zero in React Query

I am starting to learn ReactQuery. I've gone through multiple articles which mentioned that data won’t re-fetch when staleTime: Infinity and cacheTime: 0. I would like to understand how this works. From my understanding, cacheTime is the time till which the data stays in the cache before it is garbage collected/deleted. In this case as the cacheTime is set to zero, when there is component unmount, the cached data is garbage collected immediately. Now if there is window refocus (or any trigger point), as there is no data to be fetched from cache so how is it possible to not make a re-fetch and still have the data?

I read multiple articles on React Query but couldn't help myself.

Upvotes: 0

Views: 413

Answers (1)

Jakub Kotrs
Jakub Kotrs

Reputation: 6244

I think the way you are describing what you've learned, there is a missing detail. And that is that the query is mounted.

function Component() {
  useQuery({
    cacheTime: 0,
    staleTime: Infinity
  })
}

As long as Component is mounted, the query will not refetch. It will keep returning stale data when it updates.

However, when the query unmounts (meaning the component unmounts), the cache time will kick in and clean the data from memory. Next time the component mounts, it will have to refetch as you expect.

So,

{
  cacheTime: 0,
  staleTime: Infinity
}

doesn't refetch a mounted query.

Upvotes: 0

Related Questions