swr icon indicating copy to clipboard operation
swr copied to clipboard

refreshWhenHidden not working properly

Open usuallyno opened this issue 1 year ago • 2 comments

Bug report

Description / Observed Behavior

I've encountered an issue with useSWR's refreshWhenHidden prop. Due to a known behavior across browser vendors, document.visibilityState does not update to hidden when the user changes windows or applications (e.g., using alt+tab or system gestures).

In particular, the problem lies in the isVisible function located in swr/src/_internal/utils/web-preset.ts:

const isVisible = () => {
  const visibilityState = isDocumentDefined && document.visibilityState;
  return isUndefined(visibilityState) || visibilityState !== 'hidden';
}

Since document.visibilityState stays visible during window or app switches, useSWR continues to behave as if the window is in the foreground, which interferes with refreshWhenHidden behavior.

Expected Behavior

useSWR should recognize that the window has become inactive when a user switches to another application or browser tab and should stop to revalidate data refreshWhenHidden accordingly, even if document.visibilityState remains visible.

Repro Steps / Code Example

  1. Set refreshWhenHidden to false and refreshInterval to 500 in a component using useSWR.
  2. Switch to a different window or application using alt+tab or a similar gesture.
  3. Note that document.visibilityState does not update to hidden, causing a revalidation every 5 seconds.

You can also test this behavior in a minimal CodeSandbox setup to observe the issue.

Additional Context

  • useSWR version: 2.2.5
  • Browser versions tested: Chrome 131.0.6778.70 (arm64)
  • Next.js version: 12.3.4

This issue appears to be rooted in document.visibilityState handling across browsers, but any insights on improving useSWR's behavior to account for this would be appreciated.

References

https://stackoverflow.com/questions/28993157/visibilitychange-event-is-not-triggered-when-switching-program-window-with-altt

usuallyno avatar Nov 13 '24 13:11 usuallyno

We're seeing a similar issue in our app. Revalidation on window focus is not working in Chrome, but works in Safari. Here's an example: https://github.com/steviesocks/swr-bug

steviesocks avatar May 23 '25 16:05 steviesocks

any news?

usuallyno avatar Oct 15 '25 08:10 usuallyno