23 lines
798 B
TypeScript
23 lines
798 B
TypeScript
|
|
import { useEffect, useState } from 'react';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Tracks Page Visibility API state for the current document.
|
||
|
|
*
|
||
|
|
* Returns `true` when the tab is visible, `false` when hidden. Useful for
|
||
|
|
* pausing work (polling, animations, expensive DOM effects) while the tab
|
||
|
|
* is backgrounded. SSR-safe: defaults to `true` when `document` is undefined.
|
||
|
|
*/
|
||
|
|
export function usePageVisible(): boolean {
|
||
|
|
const [visible, setVisible] = useState(() =>
|
||
|
|
typeof document === 'undefined' ? true : document.visibilityState === 'visible',
|
||
|
|
);
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
const onChange = () => setVisible(document.visibilityState === 'visible');
|
||
|
|
document.addEventListener('visibilitychange', onChange);
|
||
|
|
return () => document.removeEventListener('visibilitychange', onChange);
|
||
|
|
}, []);
|
||
|
|
|
||
|
|
return visible;
|
||
|
|
}
|