Created
December 9, 2019 14:21
-
-
Save lucaspoffo/33dca43c3c5105d558073df42ccf845d to your computer and use it in GitHub Desktop.
Custom Hook to detect if the window is active.
This file contains hidden or 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 { useState, useEffect } from 'react' | |
export function useWindowActive() { | |
const [isWindowActive, setWindowIsActive] = useState(!document.hidden && document.hasFocus()) | |
function onBlur() { | |
setWindowIsActive(false) | |
} | |
function onFocus() { | |
setWindowIsActive(true) | |
} | |
function onVisibilityChange() { | |
setWindowIsActive(!document.hidden) | |
} | |
useEffect(() => { | |
window.addEventListener('blur', onBlur) | |
document.addEventListener('blur', onBlur) | |
window.addEventListener('focus', onFocus) | |
document.addEventListener('focus', onFocus) | |
document.addEventListener('visibilitychange', onVisibilityChange) | |
return () => { | |
window.removeEventListener('blur', onBlur) | |
document.removeEventListener('blur', onBlur) | |
window.removeEventListener('focus', onFocus) | |
document.removeEventListener('focus', onFocus) | |
document.removeEventListener('visibilitychange', onVisibilityChange) | |
} | |
}, []) | |
return isWindowActive | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment