日本語

How to Pause Polling in React While the Tab Is in the Background

​​React​AbortController,custom hook,TanStack Query,TypeScript,useEffectEvent,useSyncExternalStore

A screen that asks the server every 2 seconds to refresh its display keeps sending requests while another tab is in front. Nobody is looking at the screen, so the refreshed data is never seen. If you stop the timer while document.visibilityState is hidden, and send one request as soon as it becomes visible again, you can remove the requests made while the page is not visible.

I put this behavior into a custom hook, usePolling. I also compared a plain setInterval version and TanStack Query's refetchInterval, to see how each one changes the requests made while the tab is in the background.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, TanStack Query 5.105.1, and Playwright 1.63.0. I type-checked the .tsx files with tsc, converted them with esbuild, and served them from a test server written in Node.js. I switched tabs through the Chromium DevTools Protocol (the reason is explained in the last section). I did not test Firefox, Safari, mobile browsers, minimized windows, or tabs that stay in the background for more than 5 minutes.

Two browser tabs are shown at the top. In the tab whose Japanese label means "inventory status," the request count goes from 3 to 4. When the cursor clicks the other tab, whose Japanese label means "another page," the "requests received by the server" count shown on that page stays at 4. When the cursor returns to the "inventory status" tab, the count immediately becomes 5, and the number flashes pink.
Requests to the server do not increase while the tab is in the background, and one request is sent as soon as it is shown again

In the GIF, the tab labeled "inventory status" (its label is in Japanese) uses usePolling from this article and sends a request every 2 seconds. The other tab, labeled "another page" (its label is in Japanese), shows the number of requests the server has received, updated every 0.25 seconds. While I looked at the other tab for about 4 seconds, the count did not increase. The cursor, the circle showing where it clicked, and the click count in the upper right were added after recording, for explanation. A number is shown in pink only at the moment it changes.

Getting the tab visibility with usePageVisible

As described in MDN's explanation of the Page Visibility API, you can tell whether a tab is visible from document.visibilityState. When you switch to another tab or minimize the window, the value becomes hidden, and a visibilitychange event fires on document each time. MDN gives an example of an information screen that does not request updates from the server while it is not visible.

To read this value in React, use useSyncExternalStore. The official reference example for subscribing to a browser API reads navigator.onLine. Here I subscribe to visibilitychange in the same way.

ts
import { useSyncExternalStore } from 'react';

function subscribe(onChange: () => void) {
  document.addEventListener('visibilitychange', onChange);
  return () => document.removeEventListener('visibilitychange', onChange);
}

function getSnapshot() {
  return document.visibilityState === 'visible';
}

// When rendering on the server, treat the page as visible
function getServerSnapshot() {
  return true;
}

export function usePageVisible() {
  return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}

subscribe is defined outside the component because passing a new function on every render makes React subscribe again. getServerSnapshot is used only when rendering on the server and when hydrating the result. I did not test server rendering in this article.

Running the timer only while the tab is visible

usePolling uses setTimeout to schedule the next request only while the page is visible. When visible becomes false, the effect's cleanup function runs. It clears the scheduled timer and, if a request is in progress, aborts it.

ts
import { useEffect, useEffectEvent, useRef } from 'react';
import { usePageVisible } from './usePageVisible';

export function usePolling(
  poll: (signal: AbortSignal) => Promise<void>,
  intervalMs: number,
) {
  const visible = usePageVisible();
  const onPoll = useEffectEvent(poll);
  // When the last request finished (0 if none yet)
  const lastDoneRef = useRef(0);

  useEffect(() => {
    if (!visible) return; // Do not set a timer while the page is hidden

    const controller = new AbortController();
    let timerId: number | undefined;

    const tick = async () => {
      try {
        await onPoll(controller.signal);
        lastDoneRef.current = Date.now();
      } catch {
        // Errors are shown inside poll. Do nothing when the request was aborted
      }
      if (!controller.signal.aborted) {
        timerId = window.setTimeout(tick, intervalMs);
      }
    };

    // If at least intervalMs has passed since the previous request, poll right away
    const wait = Math.max(0, intervalMs - (Date.now() - lastDoneRef.current));
    timerId = window.setTimeout(tick, wait);

    return () => {
      controller.abort();
      window.clearTimeout(timerId);
    };
  }, [visible, intervalMs]);
}

There are three points to note in this code.

First, it does not use setInterval. It sets the next setTimeout after the request finishes. Even if the server takes longer than 2 seconds to respond, requests do not overlap.

Second, the wait when the tab becomes visible again. The time when the last request finished is stored in lastDoneRef. If at least intervalMs has passed since then, the hook sends a request without waiting. If the page was in the background for a long time, it sends a request as soon as it is visible again. If you only looked at another tab briefly and came back, it waits for the remaining time. In the test environment, a request finished at 2.4 seconds, the tab was hidden at 3.0 seconds, and visible again at 3.6 seconds. The next request was at 4.4 seconds. That matches the 2-second schedule used when the tab was never hidden.

Third, poll is wrapped in useEffectEvent. Inside an Effect Event, you can read the latest props and state at the time it is called. It is also not included in the effect's dependency array. So even if the caller passes a new function on every render, the timer is not restarted. As the official reference says, an Effect Event can be called only from inside an effect (or from another Effect Event).

The caller passes the received signal to fetch. When the request is aborted, the error is rethrown as is, so no error message is shown.

tsx
import { useState } from 'react';
import { usePolling } from './usePolling';
import { StatusView, type Status } from './StatusView';

export function HookStatus({ delay }: { delay: number }) {
  const [status, setStatus] = useState<Status | null>(null);
  const [error, setError] = useState<string | null>(null);

  usePolling(async (signal) => {
    try {
      const res = await fetch(`/api/status?mode=hook&delay=${delay}`, { signal });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      setStatus(await res.json());
      setError(null);
    } catch (e) {
      if (signal.aborted) throw e;
      setError(String(e));
      throw e;
    }
  }, 2000);

  return <StatusView label="usePolling" status={status} error={error} />;
}

StatusView is a component that only displays the count, the time, and the tab state. delay is how long the test server waits before it returns a response. I used it to check what happens when the tab is hidden during a request.

With plain setInterval, requests continue in the background

For comparison, I used a version that only calls setInterval inside useEffect.

tsx
useEffect(() => {
  const load = async () => {
    const res = await fetch('/api/status?mode=naive');
    setStatus(await res.json());
  };
  load();
  const id = window.setInterval(load, 2000);
  return () => window.clearInterval(id);
}, []);

I opened the page, brought another tab to the front 8 seconds later, returned to the original tab 28 seconds later, and recorded the times when the server received requests. I measured the three TanStack Query settings in the same way.

A graph that plots, for five approaches, the times when the server received requests as dots. From 8 to 28 seconds, while another tab was in front, the dots continue for the setInterval-only version and for refetchIntervalInBackground: true. For usePolling, the default TanStack Query settings, and refetchOnWindowFocus: false, there are no dots in that period. The usePolling dot at exactly 28 seconds is pink
A graph showing whether requests were sent during the 20 seconds in the background, for each approach

Here are the request counts during the 20 seconds the tab was in the background:

Approach Requests during the 20 seconds in the background Time of the first request after returning
useEffect with setInterval only 10 28.4 seconds
usePolling in this article 0 28.0 seconds
TanStack Query (default settings) 0 28.0 seconds
TanStack Query (refetchOnWindowFocus: false) 0 28.4 seconds
TanStack Query (refetchIntervalInBackground: true) 7 28.0 seconds

The setInterval version delayed the first request after the tab went to the background a little (the request after 6.4 seconds came at 9.4 seconds), and after that it kept sending requests every 2 seconds. Browsers delay timers in background tabs, but they do not stop them. According to MDN's explanation of setTimeout, Chrome checks timers in pages that have been hidden for less than 5 minutes once per second. A request every 2 seconds is longer than that interval, so it ran almost as scheduled. MDN also says that after 5 minutes, timers may be delayed to once per minute. I did not test this.

usePolling sent no requests from 8.0 seconds, when the tab went to the background, until 28.0 seconds, when it came back. The request at 28.0 seconds was sent because more than 2 seconds had passed since the last request at 6.4 seconds.

Hiding the tab during a request, and StrictMode

I made each response take 1.5 seconds and brought another tab to the front during a request, at 4.5 seconds. The request that started at 4.0 seconds was aborted when the connection was closed before the server returned a response. When I returned to the tab at 10.0 seconds, the next request started immediately.

text
--- Each request takes 1.5s
visibilitychange: 4.5s hidden, 10.0s visible
  #1 0.5s ok
  #2 4.0s aborted
  #3 10.0s ok
  #4 13.5s pending

#4 is pending because at 14 seconds, when the record was taken, it had not yet received a response.

Even when I wrapped the development build in <StrictMode>, only one request was sent right after the page opened. As the official StrictMode reference explains, during development an effect runs as "run, cleanup, run again." Right after the page opens, lastDoneRef is 0, so in the first run the timer is set with a delay of 0 ms. The cleanup clears this timer before it fires. When I hid and returned to the tab, there was also only one request.

TanStack Query stops requests in the background even with default settings

If you use useQuery from TanStack Query, you do not need to write the hook yourself. Even if you poll every 2 seconds with refetchInterval, the default for refetchIntervalInBackground is false, so no requests are sent while the tab is in the background.

tsx
const { data, error } = useQuery({
  queryKey: ['status', mode],
  queryFn: async ({ signal }): Promise<Status> => {
    const res = await fetch(`/api/status?mode=${mode}`, { signal });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return res.json();
  },
  refetchInterval: 2000,
  refetchIntervalInBackground: mode === 'query-bg',
  refetchOnWindowFocus: mode !== 'query-nofocus',
});

The request at the moment the tab returns (28.0 seconds) comes from refetchOnWindowFocus. According to TanStack Query's explanation of refetching when the window regains focus, this setting defaults to true, and it refetches when the data has become stale by the time the page is visible again. As described in TanStack Query's important defaults, if you do not set staleTime, fetched data is treated as stale immediately. By default, "returning" is detected through visibilitychange.

With refetchOnWindowFocus: false, the first request after returning came at 28.4 seconds. Requests came at 0.4, 2.4, 4.4, 6.4, and then 28.4 seconds. After returning, they stayed on the same 2-second schedule as before the tab was hidden. The request waited for the next tick, not for the moment the tab became visible.

With refetchIntervalInBackground: true, requests continued while the tab was in the background. However, the interval stretched to every 3 seconds (9.4, 12.4, and so on), which differs from the 2-second interval of the setInterval-only version. I did not investigate why it became 3 seconds.

Notes on testing tab switches with Playwright

At first, I opened the page with Playwright and tried to check the behavior by bringing another page to the front with bringToFront(). However, the original page's document.visibilityState stayed visible, and no visibilitychange event fired.

text
Playwright: 別のタブを前に出したあとの visibilityState = visible

TanStack Query's documentation also notes that if Chrome DevTools' "Emulate a focused page" is enabled, document.visibilityState stays visible and visibilitychange does not fire. Depending on the test tool or browser settings, switching tabs may not count as putting the page in the background.

For this article, I therefore did not connect Playwright to the page. Instead, I launched Chromium directly and used the HTTP endpoints of the DevTools Protocol to open a new tab (/json/new) and bring the original tab to the front (/json/activate). With this method, hidden and visible were recorded when the tabs were switched.

​Posted by 86