Course contentsShow
← React
Lesson 1781 of 2,39642. Data Fetching LibrariesFree lesson

Stale-While-Revalidate Explained

Understanding how TanStack Query serves cached data immediately while refetching in the background.

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:

  1. Immediately returns the cached data (even though it's stale)
  2. 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: data contains the cached value, isLoading is false, isFetching is true
  • After refetch: data updates with fresh value, isFetching becomes false

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.