-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathindex.ts
32 lines (27 loc) · 1.08 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import {useState} from 'react';
import {useEventListener} from '../useEventListener/index.js';
import {useMountEffect} from '../useMountEffect/index.js';
import {isBrowser} from '../util/const.js';
const isDocumentVisible = () => document.visibilityState === 'visible';
export function useDocumentVisibility(initializeWithValue: false): boolean | undefined;
export function useDocumentVisibility(initializeWithValue?: true): boolean;
/**
* Returns a boolean indicating whether the document is visible or not.
*
* @param initializeWithValue Whether to initialize with the document visibility state or
* `undefined`. _Set this to `false` during SSR._
*/
export function useDocumentVisibility(initializeWithValue = true): boolean | undefined {
const [isVisible, setIsVisible] = useState(
isBrowser && initializeWithValue ? isDocumentVisible() : undefined,
);
useMountEffect(() => {
if (!initializeWithValue) {
setIsVisible(isDocumentVisible());
}
});
useEventListener(isBrowser ? document : null, 'visibilitychange', () => {
setIsVisible(isDocumentVisible());
});
return isVisible;
}