typescriptbeginner
usePageVisibility Hook
Detects when the page is hidden or visible using the Page Visibility API.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useEffect } from 'react';
export function usePageVisibility(): boolean {
const [isVisible, setIsVisible] = useState(!document.hidden);
useEffect(() => {
const handler = () => setIsVisible(!document.hidden);
document.addEventListener('visibilitychange', handler);
return () => document.removeEventListener('visibilitychange', handler);
}, []);
return isVisible;
}
// Usage:
// const isVisible = usePageVisibility();
// useEffect(() => {
// if (isVisible) refetchData();
// }, [isVisible]);Use Cases
- Pausing animations
- Stopping polling when tab is hidden
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
usePermission Hook
Queries and tracks browser permission state for features like notifications, camera, and geolocation.
Best for: Permission-gated features
#hooks#permissions
typescriptintermediate
useGeolocation Hook
Accesses browser geolocation API with loading, error states, and watch mode support.
Best for: Location-based features
#hooks#geolocation
typescriptintermediate
useScreenWakeLock Hook
Prevents the screen from turning off using the Screen Wake Lock API.
Best for: Video playback
#hooks#wake-lock
typescriptintermediate
useFullscreen Hook
Toggle fullscreen mode on an element using the Fullscreen API with state tracking.
Best for: Video players
#hooks#fullscreen