phanpy/src/utils/usePageVisibility.js

15 lines
477 B
JavaScript
Raw Normal View History

2023-02-07 19:31:46 +03:00
import { useEffect } from 'preact/hooks';
export default function usePageVisibility(fn = () => {}, deps = []) {
useEffect(() => {
const handleVisibilityChange = () => {
const hidden = document.hidden || document.visibilityState === 'hidden';
fn(!hidden);
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () =>
document.removeEventListener('visibilitychange', handleVisibilityChange);
}, [fn, ...deps]);
}