|Kit

useDocumentVisibility

Tracks whether the page is visible or hidden, updating live as the visitor switches tabs, minimises the window or locks the screen.

useDocumentVisibility returns document.visibilityState: "hidden" while the tab is in the background, the window minimised or the screen locked, "visible" otherwise. Use it to stop work nobody can see: a polling loop, a video, a camera stream, a countdown.

import { useDocumentVisibility } from '@42-central/ui-react';

const visibility = useDocumentVisibility(); // "visible" | "hidden"

SSR-safe via useSyncExternalStore: the server and the hydration render read "visible", since a page is rendered to be looked at. On a page that hydrates in a background tab, the value flips to "hidden" right after mount.

Usage

Switch to another tab and come back. The demo adds up the time the page spent hidden.

Switch to another tab, then come back.

You haven't left yet.

Code

const visibility = useDocumentVisibility();
const hiddenAt = useRef<number | null>(null);
const [away, setAway] = useState(0);

useEffect(() => {
  if (visibility === 'hidden') {
    hiddenAt.current = Date.now();
    return;
  }
  const since = hiddenAt.current;
  if (since === null) return;
  hiddenAt.current = null;
  setAway((ms) => ms + Date.now() - since);
}, [visibility]);

Acting on the change

To do something at the moment the page hides or shows, react to the value in an effect. The kit does this itself: Camera pauses its stream (and turns the light off) when the page hides, and notifications hold their auto-dismiss timers so nothing expires unseen.

const visibility = useDocumentVisibility();

useEffect(() => {
  if (visibility === 'hidden') video.current?.pause();
}, [visibility]);

API

Takes no arguments. Returns "visible" or "hidden", the DOM's DocumentVisibilityState.

On this page