UNPKG

@supunlakmal/hooks

Version:

A collection of reusable React hooks

28 lines 1 kB
import { useState, useEffect, useRef } from 'react'; export const useThrottledState = (initialValue, delay = 500) => { const [value, setValue] = useState(initialValue); const [throttledValue, setThrottledValue] = useState(initialValue); const lastExecuted = useRef(Date.now()); useEffect(() => { let timer = null; const now = Date.now(); const timeSinceLastExecution = now - lastExecuted.current; if (timeSinceLastExecution >= delay) { setThrottledValue(value); lastExecuted.current = now; return; } else { timer = setTimeout(() => { setThrottledValue(value); lastExecuted.current = Date.now(); }, delay - timeSinceLastExecution); } return () => { if (timer) clearTimeout(timer); }; }, [value, delay]); return [throttledValue, setValue]; }; //# sourceMappingURL=useThrottledState.js.map