javascript
Custom hook to check window is visible
Returns whether the window is currently visible to the user. https://github.com/pancakeswap/pancake-frontend
import { useEffect, useState } from 'react'
const VISIBILITY_STATE_SUPPORTED = 'visibilityState' in document
function isWindowVisible() {
if (!VISIBILITY_STATE_SUPPORTED) {
return true
}
return document.visibilityState === 'visible'
}
/**
* Returns whether the window is currently visible to the user.
*/
export default function useIsWindowVisible() {
const [isVisible, setIsVisible] = useState(isWindowVisible())
useEffect(() => {
if (!VISIBILITY_STATE_SUPPORTED) return undefined
const handleVisibilityChange = () => {
setIsVisible(isWindowVisible())
}
document.addEventListener('visibilitychange', handleVisibilityChange)
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange)
}
}, [setIsVisible])
return isVisible
}
Was this helpful?
Similar Posts
- UseState hook in react
- Run a Javascript file in Terminal window
- Call custom method on form submit redux form
- Videojs check if video is playing
- Check if video is stopped or playing Javascript only
- How to Check if Arrays in a Object Are All Empty
- Check if a variable is null, empty, undefined or false Javascript