useDocumentVisibility
React Sensor Hook that tracks document.visibilityState
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
Error: Minified React error #185; visit https://react.dev/errors/185 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
API
useDocumentVisiblity
Returns
DocumentVisibilityState
: document visibility
Arguments
Argument | Description | Type | DefaultValue |
---|---|---|---|
defaultValue | default value | DocumentVisibilityState | undefined | - |