Skip to content

Instantly share code, notes, and snippets.

@milksense
Created August 3, 2021 02:50
Show Gist options
  • Save milksense/251a04a51d3b29bd1bced45058718f2a to your computer and use it in GitHub Desktop.
Save milksense/251a04a51d3b29bd1bced45058718f2a to your computer and use it in GitHub Desktop.
windowFocusedHook | React
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