Created
June 25, 2021 10:35
-
-
Save codemile/3acbe8b7c98aec5324631c02520d81a8 to your computer and use it in GitHub Desktop.
Hook that emits document visibility.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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