usePageVisible
Detect whether the page is visible. The visibilitychange event doesn't fire when restoring from the bfcache, so this hook also listens to the pageshow event to re-detect.
API
function usePageVisible(): boolean;
Results:
- Returns
trueif the page is visible, otherwisefalse.
Notes
- Returns
truein non-browser environments.
Example
The following example pauses a timer while the page is hidden (typical for pausing video).
The page is visible.
Elapsed seconds (pauses while hidden): 0
import { useEffect, useState } from "react";
import { usePageVisible } from "@lilib/hooks";
function Example() {
const visible = usePageVisible();
const [elapsed, setElapsed] = useState(0);
useEffect(() => {
if (!visible) {
// Pause while the page is hidden.
return;
}
const timer = setInterval(() => {
setElapsed((elapsed) => elapsed + 1);
}, 1000);
return () => clearInterval(timer);
}, [visible]);
return (
<div>
<div>The page is {visible ? "visible" : "hidden"}.</div>
<div>Elapsed seconds (pauses while hidden): {elapsed}</div>
</div>
);
}
export default Example;