Last active
March 8, 2023 01:35
-
-
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
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 { 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