phanpy/src/utils/usePageVisibility.js

21 lines
678 B
JavaScript
Raw Normal View History

2023-02-09 17:27:49 +03:00
import { useEffect, useRef } from 'preact/hooks';
2023-02-07 19:31:46 +03:00
export default function usePageVisibility(fn = () => {}, deps = []) {
2023-05-05 12:53:16 +03:00
const savedCallback = useRef(fn);
useEffect(() => {
savedCallback.current = fn;
}, [deps]);
2023-02-09 17:27:49 +03:00
2023-02-07 19:31:46 +03:00
useEffect(() => {
const handleVisibilityChange = () => {
const hidden = document.hidden || document.visibilityState === 'hidden';
2023-02-09 17:27:49 +03:00
console.log('👀 Page visibility changed', hidden ? 'hidden' : 'visible');
savedCallback.current(!hidden);
2023-02-07 19:31:46 +03:00
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () =>
document.removeEventListener('visibilitychange', handleVisibilityChange);
2023-02-09 17:27:49 +03:00
}, []);
2023-02-07 19:31:46 +03:00
}