React Query: What is staleTime?
What is staleTime
?
staleTime
is a configurable duration (in milliseconds) during which data returned by a query is considered up-to-date/fresh. During this period, React Query won’t automatically refetch this data when a new component using this query is rendered.
What is the default behaviour?
By default, staleTime
is 0
which means that data is considered immediately as outdated/stale as soon as it’s fetched. This ensures data is always up to date but it may lead to too many fetches which may not be ideal in all scenarios.
What value to set for staleTime
?
If you know that some piece of data (e.g., app-wide settings for the user) is unlikely to change, you can set a longer staleTime
(e.g., 20000ms / 20 seconds) to reduce unnecessary network requests.
Other times, it may make sense to leave staleTime
as 0 (e.g., rendering a news feed) so that your components always use the latest data.
When are stale queries refetched?
Stale queries are refetched automatically in the background when:
- New instances of the query mount.
- The window is refocused.
- The network is reconnected.
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment