Created
August 3, 2021 02:50
-
-
Save milksense/251a04a51d3b29bd1bced45058718f2a to your computer and use it in GitHub Desktop.
windowFocusedHook | React
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 useWindowFocused = () => { | |
const [windowIsActive, setWindowIsActive] = useState(true); | |
function handleActivity(forcedFlag) { | |
if (typeof forcedFlag === 'boolean') { | |
return forcedFlag ? setWindowIsActive(true) : setWindowIsActive(false); | |
} | |
return document.hidden ? setWindowIsActive(false) : setWindowIsActive(true); | |
} | |
useEffect(() => { | |
document.addEventListener('visibilitychange', handleActivity); | |
document.addEventListener('blur', () => handleActivity(false)); | |
window.addEventListener('blur', () => handleActivity(false)); | |
window.addEventListener('focus', () => handleActivity(true)); | |
document.addEventListener('focus', () => handleActivity(true)); | |
return () => { | |
window.removeEventListener('blur', handleActivity); | |
document.removeEventListener('blur', handleActivity); | |
window.removeEventListener('focus', handleActivity); | |
document.removeEventListener('focus', handleActivity); | |
document.removeEventListener('visibilitychange', handleActivity); | |
}; | |
}, []); | |
return { windowIsActive }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment