Skip to content

refreshWhenHidden not working properly #3039

Open
@usuallyno

Description

@usuallyno

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions