All hooks / Page, device, and user

useDocumentVisibility

101 B minified and brotliedSourceMarkdown✓ Works in all modern browsers

The page's document.visibilityState ('visible' or 'hidden'), updated when the user switches tabs, minimizes the window, or locks the screen.

Renders serverValue on the server and during hydration, then switches to the real state with no hydration mismatch.

Import

import { useDocumentVisibility } from '@vincent.ri/react-tils'
// or only this hook
import { useDocumentVisibility } from '@vincent.ri/react-tils/useDocumentVisibility'

Usage

const visibility = useDocumentVisibility()
useEffect(() => {
  if (visibility === 'hidden') return
  const id = setInterval(refresh, 5000)
  return () => clearInterval(id)
}, [visibility])

Live demo

Switch tabs or windows and come back.

visiblefocused

When to use it

Pausing polling, video, animations, or timers while the page is hidden, or refreshing data when the user comes back.

When not to

You need to know if an element is on screen; use useInView. Don't use it to save state before the page closes; listen for pagehide instead, since a hidden page may never become visible.

API

function useDocumentVisibility(serverValue?: DocumentVisibilityState): DocumentVisibilityState
ParameterDescription
serverValueState on the server and during hydration. Default 'visible'.

Browser support

UsesChromeEdgeFirefoxSafariChrome AndroidSafari iOS
Page VisibilityWidely available33+12+18+7+33+7+

First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).

Coming from another library?

Other libraries call this usePageVisibility.