How does TanStack Query's caching and staleness model work?
Answer
TanStack Query uses a sophisticated cache with staleness tracking. Key concepts: Query key: uniquely identifies a cache entry. ["user", id] is a different cache entry than ["user", 42]. staleTime: how long data is considered fresh. During this period, no background refetch occurs. Default: 0 (immediately stale). staleTime: 5 * 60 * 1000 = data stays fresh for 5 minutes. gcTime (cacheTime): how long unused cache data is retained in memory. Default: 5 minutes. refetch triggers: when stale, data is refetched on: component mount, window focus, network reconnect, manual invalidateQueries, interval (refetchInterval). Cache invalidation: queryClient.invalidateQueries({ queryKey: ["users"] }) — marks all user queries as stale and triggers background refetch for any currently rendered query. Dependent queries: useQuery({ queryKey: ["orders", userId], enabled: !!userId }) — only fetches when userId is truthy. Prefetching: queryClient.prefetchQuery loads data before navigation. Query deduplication: multiple components subscribing to the same key share one request.
Previous
What is XState and state machines in UI development?
Next
What are the patterns for sharing state between micro-frontends?
More Redux / State Management Questions
View all →- Advanced How do you architect state management for large-scale React applications?
- Advanced What is Redux-Saga and how does it differ from Thunks?
- Advanced What is XState and state machines in UI development?
- Advanced What are the patterns for sharing state between micro-frontends?
- Advanced How do you handle real-time state updates with WebSockets and Redux?