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…