Skip to content

Instantly share code, notes, and snippets.

@ayse8888
Forked from codemile/useDocVisible.tsx
Created June 25, 2021 11:16
Show Gist options
  • Save ayse8888/fa681d4502afda124d30aadeb86a5265 to your computer and use it in GitHub Desktop.
Save ayse8888/fa681d4502afda124d30aadeb86a5265 to your computer and use it in GitHub Desktop.
Hook that emits document visibility.
import {useEffect, useState} from 'react';
export const useDocVisible = () => {
const isVisible = () => document.visibilityState === 'visible';
const [visible, setVisible] = useState(isVisible());
useEffect(() => {
const onVisible = () => setVisible(isVisible());
document.addEventListener('visibilitychange', onVisible);
return () =>
document.removeEventListener('visibilitychange', onVisible);
}, []);
return visible;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment