DEV Community

Cover image for React Query : staleTime vs cacheTime
SREY
SREY

Posted on • Edited on

React Query : staleTime vs cacheTime

So in our last part we looked the basics of default configuration and also looked at the concepts of stale time and cache time, but what should be ideally the case, how to make it the best possible scenario by assigning the values to them respectively.

Ideally many of you will also think are they both inter-related? I might not have the best answer for it but lets have a look into it and find out, (TLDR : Answer is no)
Shall we?


Does Setting Any One of them Impacts other ?

staleTime basically is the time before the data fetched again from server gets stale or we may say the data that haven't been updated, as in my last part of this series I mentioned the default time of staleTime is set to be 0 in react-query hence when the data gets fetched it is considered to be stale

and hence the data gets re fetched again if you open your networks tab you will see multiple API request firing from client side. So does cacheTime gets impacted from this , no cacheTime is a length of time which removes the inactive data or stale data after a certain amount of time by default 5 mins from cache , so stale data is something that is responsible for making API request when data gets stale or when fresh or updated data is needed.


How Req query Works Works


What if cacheTime is stale ?


Let's see What scenarios rises when we go with default configurations!

  • Data Fetch: When you fetch data using React Query, the data will be considered fresh and not stale at the time of the initial fetch.

  • Immediate Staleness: Since you've set staleTime to zero, as soon as the initial data is loaded, it will be marked as stale. This means that if you try to access the same data again, React Query will consider it stale and attempt to refetch it immediately.

  • Cache Retention: Since you didn't specify a value for cacheTime, React Query will use its default behavior. By default, data will be retained in the cache for 5 minutes (cacheTime of 300,000 milliseconds). After that time elapses, the data will be automatically removed from the cache.

  • Continuous Refetching: Because the data is immediately marked as stale and React Query will try to refetch it, you'll likely see frequent network requests for the same data as long as the data remains in the cache (up to the default cacheTime of 5 minutes). This can potentially result in a high volume of network requests for the same data.

In summary, setting staleTime to zero and not specifying a custom cacheTime will lead to immediate staleness of fetched data and frequent refetching as long as the data remains in the cache, which is retained for the default 5-minute duration. This behavior might not be desirable in most cases because it can result in unnecessary network requests. You should carefully consider the appropriate values for staleTime and cacheTime based on your application's requirements to achieve the desired caching and data freshness behavior.


So What should happen if we set cacheTime lower Than staleTime

Huh! its all about timing (no puns intended)

So now If we set staleTime : 15 mins and cacheTime : 5 mins for example just grab a minute and think what should happen

If client sends a request for the first time , the backend interface sends the data requested and the staleTime set to 15 mins make data to be considered as fresh for that amount of time
But now the User on client side jumps on different application or tab , and return after 10 minutes so he should have the data to be rendered on client side should be fresh , but cacheTime as set to be 5 minutes which is lower than staleTime hence the data will not be fetched from cached data we need to make a re fetch for the data from the backend interface even though the data is not stale it is refetched it doesn't make sense, right ?


Thanks to Dominik (react-query maintainer)for this correction (This is the updated part after we had the convo on twitter)
That above thing that you thought or I thought is not correct cause cacheTime is not about something as the name suggest it is indeed something like when a user is on /me route and if he goes to a different route /feeds for example than the cacheTime get kicks in as query becomes inactive or unused hence if the user doesn't comeback to the same route/me under 5 mins which is our default time for cacheTime than the data from the cache gets removed silently and hence a manual refetch would be needed as the cacheTime or staleTime will not automatically have refetch running. Moreover in version 5 it had been renamed to gcTime and hence setting it lower than staleTime doesn't make any difference

Here is the github_issue referencing for the same

There will be many articles where you find the same reasoning on cacheTime where I got mistaken but thanks to Dominik ( React-Query maintainer) for pointing out my mistake


Configuring Stale Time & Cache Time For a Particular API request



const { data } = useQuery(['my-data'], fetchMyData, { 
  staleTime: 10 * (60 * 1000), // 10 mins 
  cacheTime: 15 * (60 * 1000), // 15 mins 
});


Enter fullscreen mode Exit fullscreen mode

Configuring StaleTime & CacheTime Globally

So if you want all of your data to be considered fresh for longer - you can! Instead of changing cacheTime and staleTime on useQuery, you'll set it on the QueryClient.



const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 10*(60*1000), // 10 mins
      cacheTime: 15*(60*1000), // 15 mins
    },
  },
});



Enter fullscreen mode Exit fullscreen mode

Meet You again with the new part of this series, if you got something valuable and if you liked it (I know cause You are reading this) please drop a feedback it will be helpful to make this journey more better.

meme

Top comments (2)

Collapse
 
netosouza22 profile image
Neto Sousa

A great content, thankx

Collapse
 
delisrey profile image
SREY

Thanks, creating something on react-query real soon!