-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Description
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
- Set
refreshWhenHiddentofalseandrefreshIntervalto500in a component usinguseSWR. - Switch to a different window or application using
alt+tabor a similar gesture. - Note that
document.visibilityStatedoes not update tohidden, 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.