Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sandeshdamkondwar/f42a4b3923e98b10c9782dbaf338dfbe to your computer and use it in GitHub Desktop.
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.
// 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