-
-
Save sandeshdamkondwar/f42a4b3923e98b10c9782dbaf338dfbe to your computer and use it in GitHub Desktop.
A custom React Hook to detect if the page is visible or not.
This file contains hidden or 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
// hooks/use-page-visibility.js | |
import { useState, useLayoutEffect } from 'react' | |
function usePageVisibility() { | |
const [isPageVisible, setIsPageVisible] = useState(!document.hidden) | |
useLayoutEffect(() => { | |
const handleVisibility = () => { | |
setIsPageVisible(!document.hidden) | |
} | |
document.addEventListener('visibilitychange', handleVisibility) | |
return () => { | |
document.removeEventListener('visibilitychange', handleVisibility) | |
} | |
}, []) | |
return { isPageVisible } | |
} | |
export default usePageVisibility |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment