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

Automatic Refetch on Window Focus

How TanStack Query refetches stale queries when users return to the browser tab.

Automatic Refetch on Window Focus

What you'll learn: How TanStack Query automatically refreshes stale data when you switch back to your browser tab.

The Background Tab Problem

Imagine you're shopping online, open a new tab to check your email, spend 10 minutes there, then return to the shopping site. Without automatic refetching, you might see outdated prices or inventory—products could have sold out while you were away.

TanStack Query solves this by detecting when users return to your app and automatically refetching any stale queries in the background.

How It Works

When you configure a query with staleTime, TanStack Query marks it as stale after that duration expires. By default, whenever the browser window regains focus (user clicks back on the tab), TanStack Query checks all active queries:

  • If a query is stale, it automatically refetches fresh data
  • If a query is still fresh (within staleTime), it does nothing
const { data } = useQuery({
  queryKey: ['products'],
  queryFn: fetchProducts,
  staleTime: 30000, // 30 seconds
});

If a user leaves this tab for 40 seconds and returns, the products list automatically refetches. If they return after 20 seconds, nothing happens because the data is still fresh.

Controlling the Behavior

You can disable this feature per-query:

useQuery({
  queryKey: ['static-config'],
  queryFn: fetchConfig,
  refetchOnWindowFocus: false, // Disable auto-refetch
});

Or globally in your QueryClient setup to change the default for all queries.

Why This Matters

This feature ensures users always see current data without manual refresh buttons. It's especially valuable for real-time pricing, inventory, notifications, or any data that changes frequently.

Key Takeaway: TanStack Query automatically refetches stale queries when users return to your tab, keeping data fresh without any manual intervention—but only if the data has exceeded its staleTime.