Skip to main content

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 true if the page is visible, otherwise false.

Notes​

  • Returns true in 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;