usePageVisibility

Provides the current visibility state of the document using the Page Visibility API.

Tip

Use this hook to pause expensive operations—like WebSocket heartbeats, long-polling, or complex animations—when the user switches tabs to save battery and network resources.

Installation

bash

Description

Synchronizes with the document's visibility state (whether the tab is active/focused or hidden/minimized). It uses useSyncExternalStore for high-performance subscription to the visibilitychange event, making it ideal for pausing videos, stopping polling, or analytics.

Return values

NameTypeDescription
isVisiblebooleanDerived boolean: true if visibilityState is 'visible'.
visibilityStateDocumentVisibilityStateThe raw API value: 'visible', 'hidden', etc.

Demo

Page Visibility

Status: visibleVisible ✅Try switching tabs and coming back to see the state change.

Source code

tsx