Refetch Intervals for Polling
What you'll learn: How to use refetchInterval to automatically fetch fresh data at regular intervals for real-time updates.
The Problem
Sometimes your app needs continuously updated data—think sports scores, stock prices, or server status dashboards. You could manually trigger refetches, but wouldn't it be nice if TanStack Query could automatically poll your API at regular intervals?
What is Polling?
Polling means repeatedly checking for new data at fixed time intervals. It's like checking your mailbox every 10 minutes instead of waiting for someone to notify you when mail arrives.
The refetchInterval Option
TanStack Query provides refetchInterval to enable polling. Pass a number (in milliseconds) to specify how often the query should automatically refetch:
const { data } = useQuery({
queryKey: ['dashboard-stats'],
queryFn: fetchDashboardStats,
refetchInterval: 5000, // Refetch every 5 seconds
});
Now your data updates every 5 seconds automatically—no manual intervention needed!
Conditional Polling
You can also pass a function that returns a number or false to control polling dynamically:
const { data } = useQuery({
queryKey: ['live-score', gameId],
queryFn: () => fetchGameScore(gameId),
refetchInterval: (data) => {
// Stop polling if game is finished
return data?.status === 'finished' ? false : 3000;
},
});
Polling While Window is Inactive
By default, polling stops when the window loses focus. Use refetchIntervalInBackground: true to keep polling even when the user switches tabs.
Key Takeaway: Use refetchInterval to automatically poll your API at regular intervals, creating real-time data experiences without manual refetch triggers—perfect for dashboards, live feeds, and monitoring interfaces.