Skip to content

Instantly share code, notes, and snippets.

@lucaspoffo
Created December 9, 2019 14:21
Show Gist options
  • Save lucaspoffo/33dca43c3c5105d558073df42ccf845d to your computer and use it in GitHub Desktop.
Save lucaspoffo/33dca43c3c5105d558073df42ccf845d to your computer and use it in GitHub Desktop.
Custom Hook to detect if the window is active.
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