Background Refetching and Stale-While-Revalidate
What you'll learn: How modern data-fetching libraries keep your UI fast by showing stale data instantly while refetching fresh data in the background.
The Problem with Always Waiting
With manual useEffect fetching, you typically show a loading spinner every time you need fresh data. This creates a frustrating user experience: click a tab, see a spinner. Switch back to the previous tab, see the spinner again even though you just looked at that data seconds ago.
Stale-While-Revalidate: The Best of Both Worlds
The stale-while-revalidate pattern works like this:
- Show cached (stale) data immediately from memory
- Simultaneously trigger a background refetch for fresh data
- When fresh data arrives, silently update the UI
Think of it like a news app: you see yesterday's cached headlines instantly when you open the app, but new headlines quietly load in the background and appear without disrupting your reading.
Automatic Background Refetching
Libraries like TanStack Query automatically refetch stale data when:
- The browser window regains focus (user comes back from another tab)
- The network reconnects (user's WiFi comes back online)
- A time interval elapses (configurable, like every 30 seconds)
You never write these event listeners yourself—the library handles it. Your data stays fresh without you thinking about it, and users never see unnecessary loading states for data they've already seen.
This is impossible to replicate cleanly with manual useEffect fetching without significant boilerplate for caching, focus listeners, online/offline detection, and timestamp tracking.
Key Takeaway: Stale-while-revalidate shows cached data instantly while fetching fresh data in the background, eliminating loading spinners for data users have already seen and keeping the UI snappy without manual effort.