UNPKG

@primer/components

Version:
38 lines (35 loc) 962 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useSafeTimeout; var _react = require("react"); /** * Safely call `setTimeout` and `clearTimeout` within a component. * * This hook ensures that all timeouts are cleared when the component unmounts. */ function useSafeTimeout() { const timers = (0, _react.useRef)(new Set()); const safeSetTimeout = (0, _react.useCallback)((handler, timeout, ...args) => { const id = window.setTimeout(handler, timeout, ...args); timers.current.add(id); return id; }, []); const safeClearTimeout = (0, _react.useCallback)(id => { clearTimeout(id); timers.current.delete(id); }, []); (0, _react.useEffect)(() => { return () => { // eslint-disable-next-line react-hooks/exhaustive-deps for (const id of timers.current) { clearTimeout(id); } }; }, []); return { safeSetTimeout, safeClearTimeout }; }