Skip to content

Instantly share code, notes, and snippets.

@dazulu
Last active October 3, 2020 22:16
Show Gist options
  • Save dazulu/61ca730c4ac8c5186dd8675f9dc1794c to your computer and use it in GitHub Desktop.
Save dazulu/61ca730c4ac8c5186dd8675f9dc1794c to your computer and use it in GitHub Desktop.
Hook for detecting if page loses/regains focus
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