Stale-While-Revalidate Explained
What you'll learn: How TanStack Query delivers instant responses by showing cached data while simultaneously fetching fresh data in the background.
The Core Pattern
Stale-while-revalidate is the magic behind TanStack Query's snappy user experience. When you request data that exists in cache but is considered "stale" (based on staleTime), TanStack Query does both things at once:
- Immediately returns the cached data (even though it's stale)
- Triggers a background refetch to get fresh data
This means users see something instantly instead of waiting for a loading spinner, while the app quietly updates to the latest data when the fetch completes.
The Coffee Shop Analogy
Imagine you ask your friend "What's the lunch special?" They immediately tell you "Yesterday it was pasta" (cached, stale data), then walk over to check the menu board and come back saying "Actually, today it's pizza" (fresh data). You got an instant answer and the correct one—just with a brief delay on accuracy.
How It Works in Practice
When you call useQuery and the data is stale:
- First render:
datacontains the cached value,isLoadingisfalse,isFetchingistrue - After refetch:
dataupdates with fresh value,isFetchingbecomesfalse
The UI never shows a loading state for subsequent requests—it shows old data, then seamlessly updates. This is vastly better UX than refetching from scratch every time.
Key Takeaway: Stale-while-revalidate gives users instant feedback with cached data while ensuring they eventually get fresh data through background refetching—the best of both speed and accuracy.