useDocumentVisibility
跟踪 document.visibilityState 的 React Hook
Usage
实时编辑器
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>; }
结果
Loading...
API
useDocumentVisiblity
Returns
DocumentVisibilityState
: 文档可见性
Arguments
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
defaultValue | 默认值 | DocumentVisibilityState | undefined | - |