Member-only story
React Query: cacheTime vs staleTime
Don’t have a premium account? You can also find this article here.
If you ran upon this thread, you probably need help with setting up a great caching strategy using React Query (very recently renamed to TanStack Query). In this short article, I'll try to clarify the most common sources of confusion around cacheTime
and staleTime
, then conclude with a few opinionated recommendations as to how to use it with React Query.
Terminology
As their English names might (very remotely) imply, cacheTime
and staleTime
are here to allow us to limit the number of HTTP queries sent to our servers and ultimately optimize our users' experience.
More specifically, cacheTime
determines for how long a certain response is supposed to stay in cache before it gets garbage-collected.
Similarly, staleTime
determines for how long a certain response will still be considered fresh (or not stale), dismissing the need for a new request.
To rephrase it, then, cacheTime
relates to the expiration of a specific value, while staleTime
will be expiring the validity of a certain query.
React Query defaults
If not set otherwise, React Query comes out of the box with a cacheTime
of 5 minutes and a staleTime
set to zero. This is very important to keep in mind!
If you want to dig deeper, I do advise you to visit their docs. They have a dedicated page for caching examples and, overall, very didactic explanations.
But what does it mean concretely? It means that, by default, React Query will always cache your request responses for up to 5 minutes after they've been done. The advantage is that, when the user tries to fetch from the back-end a second time, React Query will serve the last value almost instantly.
However, as our default for staleTime
is set to zero, React Query will consider our request as stale (or not fresh) and trigger the second call in the background. And, once the call is finished, it will update our state with the freshly new data coming from the back-end.
The advantage of using this strategy is the responsiveness provided to our users. We first optimistically provide them with the values…