useDocumentVisibility
React Sensor Hook that tracks document.visibilityState
useDocumentVisibility reactively tracks whether the page is visible or hidden using the Page Visibility API. It returns the current DocumentVisibilityState ("visible" or "hidden") and updates automatically when the user switches tabs or minimizes the browser. You can provide a default value for the initial state.
When to Use
- Pausing animations, videos, or timers when the user navigates away from the tab
- Showing a “welcome back” message or refreshing stale data when the user returns
- Reducing network requests or resource consumption while the page is in the background
Notes
- SSR-safe: Accepts a
defaultValueparameter (e.g."hidden") that is used during server-side rendering whendocumentis not available. - Lightweight: Listens to the
visibilitychangeevent ondocumentand cleans up the listener on unmount. - See also
useWindowFocusfor tracking whether the browser window itself has focus (vs. just tab visibility).
Usage
Live Editor
function Demo() { const visibility = useDocumentVisibility("hidden"); const [message, setMessage] = useState( "💡 Minimize the page or switch tab then return", ); useEffect(() => { if (visibility === "visible") { setTimeout(() => { setMessage("🎉 Welcome back!"); }, 2000); } else { setTimeout(() => { setMessage("🥰 Take a break"); }, 2000); } }, [visibility]); return <div>{message}</div>; };
Result
API
useDocumentVisiblity
Returns
DocumentVisibilityState: document visibility
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| defaultValue | default value | DocumentVisibilityState | undefined | - |