UNPKG

use-throttle

Version:
25 lines (20 loc) 585 B
import { useState, useEffect, useRef } from 'react'; export const useThrottle = (value, limit) => { const [throttledValue, setThrottledValue] = useState(value); const lastRan = useRef(Date.now()); useEffect( () => { const handler = setTimeout(function() { if (Date.now() - lastRan.current >= limit) { setThrottledValue(value); lastRan.current = Date.now(); } }, limit - (Date.now() - lastRan.current)); return () => { clearTimeout(handler); }; }, [value, limit] ); return throttledValue; };