Archived
Initial commit
Next.js + Express event management app for Hope Family Church.
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
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]);
|
||||
}
|
||||
Reference in New Issue
Block a user