Rooks
HooksEvent Handling

useDocumentVisibilityState

Returns the document visibility state and updates when it changes.

About

useDocumentVisibilityState reports whether the current document is visible or hidden. It is useful for pausing nonessential work while a tab is in the background.

Example

import { useDocumentVisibilityState } from "rooks";

export default function VisibilityStatus() {
  const visibility = useDocumentVisibilityState();

  return (
    <p>Document status: {visibility === null ? "not available" : visibility}</p>
  );
}

Parameters

This hook has no parameters.

Return value

It returns Document["visibilityState"] | null. The value is null during server rendering and otherwise mirrors document.visibilityState.

Behavior and lifecycle

The hook uses React's external-store subscription contract. It reads the current snapshot from document.visibilityState, subscribes to visibilitychange, and removes that listener on unmount. Multiple transitions are reported as the browser emits them.

Compatibility and accessibility

The server snapshot is null; React replaces it with the browser snapshot after hydration. Do not treat a hidden document as proof that the user left the page. If visibility changes affect the interface, announce meaningful changes without repeatedly interrupting assistive-technology users.

On this page