@primer/react
Version:
An implementation of GitHub's Primer Design System using React
31 lines (30 loc) • 817 B
JavaScript
import { useCallback, useEffect, useRef } from "react";
//#region src/hooks/useSafeTimeout.ts
/**
* Safely call `setTimeout` and `clearTimeout` within a component.
*
* This hook ensures that all timeouts are cleared when the component unmounts.
*/
function useSafeTimeout() {
const timers = useRef(/* @__PURE__ */ new Set());
const safeSetTimeout = useCallback((handler, timeout, ...args) => {
const id = window.setTimeout(handler, timeout, ...args);
timers.current.add(id);
return id;
}, []);
const safeClearTimeout = useCallback((id) => {
clearTimeout(id);
timers.current.delete(id);
}, []);
useEffect(() => {
return () => {
for (const id of timers.current) clearTimeout(id);
};
}, []);
return {
safeSetTimeout,
safeClearTimeout
};
}
//#endregion
export { useSafeTimeout as default };