ilokesto

usePageVisibility

usePageVisibility returns whether document.visibilityState is "visible". It updates on the document's visibilitychange event. This API is unreleased and is not included in the current published version.

import { usePageVisibility } from '@ilokesto/utilinent/hooks';

function VisibilityStatus() {
  const isVisible = usePageVisibility();
  return <p>{isVisible ? 'Visible' : 'Hidden or awaiting hydration'}</p>;
}

Signature

function usePageVisibility(): boolean;

The hook takes no arguments. true means the document is visible; false means it is hidden, or the server/hydration fallback is still in use. Document visibility is not window focus or element intersection visibility.

SSR and hydration

  • Server rendering returns false without accessing document.
  • The first hydration render also returns false, even in a visible tab, so it matches the server markup. React then reads the actual document state.
  • A client-only mount reads the current document state immediately.
  • Unrelated rerenders keep the same subscription. Each mounted consumer owns one listener; unmount and Strict Mode cleanup remove it.

Pause optional consumer work

The hook only reports state. The consumer owns timers, polling, retries, data caches, and cancellation. In this example, the component creates and clears its own timer; the hook never runs the work.

import { useEffect, useState } from 'react';
import { usePageVisibility } from '@ilokesto/utilinent/hooks';

function VisibleCounter() {
  const isVisible = usePageVisibility();
  const [ticks, setTicks] = useState(0);

  useEffect(() => {
    if (!isVisible) {
      return;
    }
    const timer = window.setInterval(() => {
      setTicks((previous) => previous + 1);
    }, 1000);
    return () => window.clearInterval(timer);
  }, [isVisible]);

  return <output>{ticks}</output>;
}

Open this component in a browser and switch to another tab, then return. The counter pauses while hidden and resumes from its previous value; it does not catch up on missed ticks. Unmounting clears the consumer's timer. Changing the return value alone does not cancel work already started by other code: implement that policy in the consumer's effect cleanup.

On this page