Last active
October 3, 2020 22:16
-
-
Save dazulu/61ca730c4ac8c5186dd8675f9dc1794c to your computer and use it in GitHub Desktop.
Hook for detecting if page loses/regains focus
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 React from "react"; | |
const useWindowFocus = () => { | |
const [focused, setFocused] = React.useState(false); | |
const callback = ({ type }: FocusEvent) => { | |
const value = type === "blur" ? false : true; | |
setFocused(value); | |
}; | |
React.useEffect(() => { | |
window.addEventListener("focus", callback); | |
window.addEventListener("blur", callback); | |
return () => { | |
window.removeEventListener("focus", callback); | |
window.removeEventListener("blur", callback); | |
}; | |
}, []); | |
return focused; | |
}; | |
export default useWindowFocus; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment