30% offEnding soon
usePageVisibilityLoading saved progress…

usePageVisibility

Page visibility tells you whether the current document is visible to the user or hidden in a background tab. Build usePageVisibility so a component can pause expensive work while hidden and resume it when visible again. The hook reads the Page Visibility API, reacts to its document event, and remains safe when the API is unavailable.

Signature

function usePageVisibility(
  defaultValue?: 'visible' | 'hidden' // defaults to 'visible'
): 'visible' | 'hidden';

Examples

function VideoPlayer() {
  const visibility = usePageVisibility();
  return <video data-paused={visibility === 'hidden'} />;
}

// document.visibilityState === 'visible' -> 'visible'
// visibilitychange after the tab is hidden -> 'hidden'
// The API is unavailable, so the fallback is returned.
usePageVisibility();         // 'visible'
usePageVisibility('hidden'); // 'hidden'

Notes

  • Use the document as the authority. When document.visibilityState is available, return its current 'visible' or 'hidden' value even when that differs from defaultValue.
  • Read on every event. Subscribe to document's visibilitychange event and read document.visibilityState inside the handler; do not reuse the mount-time value.
  • Handle unsupported environments. If document or document.visibilityState is unavailable, return defaultValue without throwing.
  • Subscribe once and clean up. Remove the exact listener function on unmount, and do not add another listener merely because the hook rerenders.
  • Use the visibility API only. Do not poll and do not infer document visibility from window blur or focus events.