UNPKG

@modern-kit/react

Version:
39 lines (35 loc) 1.12 kB
import { useRef, useCallback, useEffect } from 'react'; import { usePreservedCallback } from '../usePreservedCallback/index.mjs'; import { isNumber } from '@modern-kit/utils'; const getTimeoutOptions = (options) => { return isNumber(options) ? { delay: options, enabled: true } : { delay: options.delay, enabled: options?.enabled ?? true }; }; function useTimeout(callback, options) { const timeoutRef = useRef(); const callbackAction = usePreservedCallback(callback); const { delay, enabled } = getTimeoutOptions(options); const set = useCallback(() => { timeoutRef.current = window.setTimeout(callbackAction, delay); }, [callbackAction, delay]); const clear = useCallback(() => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); timeoutRef.current = null; } }, []); const reset = useCallback(() => { clear(); set(); }, [clear, set]); useEffect(() => { if (!enabled) return; set(); return () => clear(); }, [set, clear, enabled]); return { set, reset, clear }; } export { useTimeout }; //# sourceMappingURL=index.mjs.map