π React Query Data Lifecycle with staleTime:
-
Data is fetched
β React Query stores it in the cache and marks it as fresh β -
During
staleTimeperiod
β The data stays fresh
β No automatic re-fetching happens even on tab focus or remount -
After
staleTimepasses
β The data becomes stale β οΈ
β Now React Query may trigger a background re-fetch when:-
You refocus the window
-
You re-mount the component
-
Network reconnects
-
-
Manual refetching always works
β You can still manually callrefetch()anytime, even when data is fresh
Query Key
useQuery({
queryKey: ['user'], // Unique identity
queryFn: fetchUser, // The function to run
});If you use this elsewhere with the same key, React Query:
- will reuse cached data if itβs still fresh
- will refetch if itβs stale