Skip to content

Instantly share code, notes, and snippets.

@viclafouch
Last active March 3, 2024 00:54
Show Gist options
  • Save viclafouch/52a8a6409c14220492d0183f509c76cd to your computer and use it in GitHub Desktop.
Save viclafouch/52a8a6409c14220492d0183f509c76cd 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