This repository has been archived on 2026-11-23. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
hope-events/frontend/src/hooks/useVisiblePolling.ts
T
joshua 3d381944d2 Initial commit
Next.js + Express event management app for Hope Family Church.
2026-07-23 15:26:47 +02:00

34 lines
1.1 KiB
TypeScript

import { useEffect, useRef } from "react";
/**
* Runs `callback` every `intervalMs` while the tab is visible. Skips ticks while the
* tab is backgrounded (document.hidden) to avoid polling for no one, and fires an
* immediate refetch the moment the tab becomes visible again so data isn't stale on
* return. Does NOT call `callback` on mount — callers should do their own initial load.
*/
export function useVisiblePolling(callback: () => void, intervalMs: number, enabled: boolean = true) {
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
useEffect(() => {
if (!enabled) return;
const id = setInterval(() => {
if (document.hidden) return;
callbackRef.current();
}, intervalMs);
const onVisibilityChange = () => {
if (!document.hidden) callbackRef.current();
};
document.addEventListener("visibilitychange", onVisibilityChange);
return () => {
clearInterval(id);
document.removeEventListener("visibilitychange", onVisibilityChange);
};
}, [intervalMs, enabled]);
}