@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
36 lines (33 loc) • 1.04 kB
JavaScript
import { useRef, useEffect, useCallback } from 'react';
const useTimeout = (callback, timeout = 0) => {
const idleRef = useRef(true);
const timerIdRef = useRef(null);
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
const isIdle = useCallback(() => idleRef.current, []);
const schedule = 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 = useCallback(() => {
idleRef.current = true;
if (timerIdRef.current !== null) {
clearTimeout(timerIdRef.current);
timerIdRef.current = null;
}
}, []);
return {
isIdle,
schedule,
cancel,
};
};
export { useTimeout };