UNPKG

feats

Version:

A comprehensive TypeScript utility library featuring fluent text building, type-safe switching, duration utilities, React hooks, and extended array/object prototypes for modern JavaScript development.

69 lines (65 loc) 2.13 kB
import { useRef, useEffect, useCallback, useMemo } from 'react'; /** * React hook for managing a single timeout with manual control. * Automatically clears the timeout on component unmount. */ function useTimeout() { const timeoutRef = useRef(null); useEffect(() => { return clear; }, []); const handle = useCallback(() => { var _a; (_a = timeoutRef.current) === null || _a === void 0 ? void 0 : _a.method(); timeoutRef.current = null; }, []); const clear = useCallback(() => { if (timeoutRef.current) { clearTimeout(timeoutRef.current.id); timeoutRef.current = null; } }, []); const set = useCallback((handler, time) => { clear(); const id = setTimeout(handle, time); timeoutRef.current = { id, method: handler, }; }, [clear, handle]); const dispatch = useCallback(() => { var _a; const method = (_a = timeoutRef.current) === null || _a === void 0 ? void 0 : _a.method; clear(); method === null || method === void 0 ? void 0 : method(); }, [clear]); return useMemo(() => ({ set, clear, dispatch }), [set, clear, dispatch]); } /** * React hook for managing an interval with manual control. * Automatically clears the interval on component unmount. */ function useInterval() { const intervalRef = useRef(null); useEffect(() => clear, []); const clear = useCallback(() => { if (intervalRef.current) { clearInterval(intervalRef.current.id); intervalRef.current = null; } }, []); const set = useCallback((handler, interval) => { clear(); const id = setInterval(() => { var _a; (_a = intervalRef.current) === null || _a === void 0 ? void 0 : _a.method(); }, interval); intervalRef.current = { id, method: handler, }; }, [clear]); return useMemo(() => ({ set, clear }), [set, clear]); } export { useInterval, useTimeout }; //# sourceMappingURL=react.mjs.map