Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Caching and Staleness

Polling and Background Refetching

Keep data live with refetchInterval: fixed and dynamic intervals, stopping when a job finishes, pausing in background tabs, and when to prefer websockets.

Some data changes on the server without anything happening in your app: the status of a long-running export, a build, a payment, the number of people online. The triggers in the previous lesson will not help, because the user did nothing. For these cases TanStack Query offers polling: a timer that refetches the query at an interval. It is a single option, refetchInterval.

A fixed interval

JSX
useQuery({
  queryKey: ["online-users"],
  queryFn: fetchOnlineUsers,
  refetchInterval: 5000,   // every 5 seconds
});

The timer runs while the query is active (observed by a mounted component). When the component unmounts, polling stops. Each tick is a normal background refetch: old data remains on screen, isFetching flips to true, and data updates only if the response differs (structural sharing means unchanged data causes no re-render).

Background tabs

By default, polling pauses when the tab is in the background, because refreshing a page nobody sees wastes bandwidth and server capacity. If you really need it to continue (a dashboard on a wall display, a title that shows unread counts), opt in:

JSX
useQuery({
  queryKey: ["unread"],
  queryFn: fetchUnread,
  refetchInterval: 30000,
  refetchIntervalInBackground: true,
});

A dynamic interval: stop when done

The real power is that refetchInterval can be a function that receives the query and returns a number (milliseconds) or false to stop. That is the standard solution for "wait until the job is finished":

Poll until a job finishes

Press Start. The bar fills in four steps, one per poll, then the function returns false, and the polling stops by itself. No useEffect, no setInterval, no cleanup. The function form also makes it easy to slow down over time (exponential back-off) or to stop on error:

JavaScript
refetchInterval: (query) => {
  if (query.state.status === "error") return false;
  const attempt = query.state.dataUpdateCount;       // how many successful fetches so far
  return Math.min(1000 * 2 ** attempt, 30000);       // 1s, 2s, 4s ... capped at 30s
},

Polling and the stale/fresh clock

Interval refetches ignore staleTime. If you set refetchInterval: 5000 and staleTime: 60000, the query still refetches every five seconds, because the timer is an explicit instruction. Keep staleTime for event-driven triggers and use the interval only where you really need live data.

Combining with other tools

  • Pause when something else is loading: use enabled with a flag such as !isSaving so polling does not race with a pending mutation.
  • Poll after a mutation: a common pattern is "start the job, then poll its status" with a query keyed by the job id returned from the mutation (enabled until the id exists, see Dependent Queries).
  • Manual refresh: refetch() and invalidation still work, and the interval timer restarts from that moment.

Polling versus push

Polling is simple and works everywhere, but it has a cost: latency up to one interval, and constant requests even when nothing changes. Push channels (WebSockets, Server-Sent Events) deliver changes the moment they happen. The good news is that you can combine them with Query: let the socket tell you what changed, and update the cache.

JavaScript
socket.on("todo:updated", (todo) => {
  queryClient.setQueryData(["todos", "detail", todo.id], todo);
  queryClient.invalidateQueries({ queryKey: ["todos", "list"] });
});

This is the "invalidate on event" pattern. It keeps all your read logic in queries (caching, loading and error states, deduplication) and uses the socket only as a signal, as in Updating the Cache from Responses. Choose polling for status checks and low-frequency data. Choose push when you need low latency or the server has many clients.

Practical guidance

Goal Setting
Wait for a job to finish Function returning false at the end
Gentle live dashboard refetchInterval: 30000
Must keep going in a hidden tab refetchIntervalInBackground: true (use sparingly)
Avoid hammering an unhealthy server Back-off function, stop on error
Update only when data matters Pair with select to limit re-renders

Always pick the longest interval users can tolerate. Ten users polling every second is ten requests per second; ten thousand users is ten thousand.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you stop polling when a job is complete?

    A function receives the query and returns the next delay in ms, or false to stop.
  2. 2. A tab goes into the background. What does polling do by default?

    refetchIntervalInBackground is false by default.
  3. 3. Does staleTime stop interval refetches while the data is still fresh?

    refetchInterval is an explicit timer and ignores staleness.
  4. 4. When might you prefer a WebSocket to polling?

    Push delivers changes immediately and avoids useless requests. Use the events to update or invalidate the cache.

Summary

  • refetchInterval refetches an active query on a timer; unmounting stops it.
  • Polling pauses in background tabs unless refetchIntervalInBackground is true.
  • A function value lets you stop at the end of a job, back off or react to errors.
  • Interval refetches ignore staleTime; choose the longest acceptable interval.
  • Push channels can drive setQueryData or invalidateQueries instead of polling.

Next: Retries and Error Handling