# useDocumentVisibility (/docs/hooks/use-document-visibility)





`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.

```tsx
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 [#usage]

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

<Preview code="&#x22;const visibility = useDocumentVisibility();\nconst hiddenAt = useRef<number | null>(null);\nconst [away, setAway] = useState(0);\n\nuseEffect(() => {\n  if (visibility === 'hidden') {\n    hiddenAt.current = Date.now();\n    return;\n  }\n  const since = hiddenAt.current;\n  if (since === null) return;\n  hiddenAt.current = null;\n  setAway((ms) => ms + Date.now() - since);\n}, [visibility]);&#x22;">
  <DocumentVisibilityDemo />
</Preview>

## Acting on the change [#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`](/docs/camera) pauses its stream (and turns the light off) when the page hides, and [notifications](/docs/notification) hold their auto-dismiss timers so nothing expires unseen.

```tsx
const visibility = useDocumentVisibility();

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

## API [#api]

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