useVisibilityChange
A hook that tracks whether the document is visible or not
Example
import useVisibilityChange from "@/hooks/useVisibilityChange";
import { useEffect, useState } from "react";
export default function UseVisibilityChangeExample() {
const isDocumentVisible = useVisibilityChange();
const [tabAwayCount, setTabAwayCount] = useState(0);
useEffect(() => {
if (isDocumentVisible === false) {
setTabAwayCount(tabAwayCount + 1);
}
}, [isDocumentVisible]);
return (
<div className="text-ctp-text">
<p>Tab away count: {tabAwayCount}</p>
</div>
);
}
Code
import { useSyncExternalStore } from "react";
const useVisibilityChangeSubscribe = (callback: (event: Event) => void) => {
document.addEventListener("visibilitychange", callback);
return () => {
document.removeEventListener("visibilitychange", callback);
};
};
const getVisibilityChangeSnapshot = () => {
return document.visibilityState;
};
const getVisibilityChangeServerSnapshot = () => {
throw Error("useVisibilityChange is a client-only hook");
};
/**
* A hook that tracks whether the document is visible or not
* @returns {boolean} true if document is visible, false otherwise
*/
export default function useVisibilityChange(): boolean {
const visibilityState = useSyncExternalStore(
useVisibilityChangeSubscribe,
getVisibilityChangeSnapshot,
getVisibilityChangeServerSnapshot,
);
return visibilityState === "visible";
}