No matter component mounts or unmounts, I don't want an API call for 2 mins after the first time get data
That is what staleTime
is doing. staleTime
tells you how fresh you data is. It is very similar to Cache-Control: max-age=120
.
So if you set staleTime: 120000
, in your example, you're guaranteed to not get another network request for two minutes after the first successful one.
cacheTime
is something totally different. Think about it as a garbage-collect time. It basically describes how long data should be kept in the cache before it can be garbage collected. This is only relevant for unused queries, because active queries can per definition not be garbage collected.
I have also outlined this differences in my blog:
StaleTime: The duration until a query transitions from fresh to stale. As long as the query is fresh, data will always be read from the cache only - no network request will happen! If the query is stale (which per default is: instantly), you will still get data from the cache, but a background refetch can happen under certain conditions.
CacheTime: The duration until inactive queries will be removed from the cache. This defaults to 5 minutes. Queries transition to the inactive state as soon as there are no observers registered, so when all components which use that query have unmounted.
I used this but it does not call API after 2 min
This is something totally different. When staleTime
elapses, your data is marked as stale - but that doesn't mean it will be instantly refetched. staleTime
defaults to zero
so that wouldn't work at all.
If you want to fetch every 2 minutes, set a refetchInterval
:
refetchInterval: 120000