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
Loading...
API
useDocumentVisiblity
Returns
DocumentVisibilityState
: document visibility
Arguments
Argument | Description | Type | DefaultValue |
---|---|---|---|
defaultValue | default value | DocumentVisibilityState | undefined | - |