Skip to content

Instantly share code, notes, and snippets.

@mtorre4580
Last active March 8, 2023 01:35
Show Gist options
  • Save mtorre4580/b4d26d53b6cc4f0ab29bd0c5c9c453df to your computer and use it in GitHub Desktop.
Save mtorre4580/b4d26d53b6cc4f0ab29bd0c5c9c453df to your computer and use it in GitHub Desktop.
Hook to check the current visibility of the page using the API Page Visibility
import { useEffect, useState } from "react";
/**
* Hook to check the current visibility of the page
* Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
* @returns boolean
*/
const useVisibilityChange = () => {
const [isVisible, setIsVisible] = useState(true);
useEffect(() => {
const handleOnVisibility = () => {
setIsVisible(document.visibilityState === 'visible');
};
document.addEventListener("visibilitychange", handleOnVisibility);
return () => {
document.removeEventListener("visibilitychange", handleOnVisibility);
};
}, []);
return isVisible;
};
export default useVisibilityChange;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment