UNPKG

@winglet/react-utils

Version:

React utility library providing custom hooks, higher-order components (HOCs), and utility functions to enhance React application development with improved reusability and functionality

38 lines (34 loc) 1.08 kB
'use strict'; var react = require('react'); const useTimeout = (callback, timeout = 0) => { const idleRef = react.useRef(true); const timerIdRef = react.useRef(null); const callbackRef = react.useRef(callback); react.useEffect(() => { callbackRef.current = callback; }, [callback]); const isIdle = react.useCallback(() => idleRef.current, []); const schedule = react.useCallback(() => { idleRef.current = false; if (timerIdRef.current !== null) clearTimeout(timerIdRef.current); timerIdRef.current = setTimeout(() => { idleRef.current = true; timerIdRef.current = null; callbackRef.current(); }, timeout); }, [timeout]); const cancel = react.useCallback(() => { idleRef.current = true; if (timerIdRef.current !== null) { clearTimeout(timerIdRef.current); timerIdRef.current = null; } }, []); return { isIdle, schedule, cancel, }; }; exports.useTimeout = useTimeout;