UNPKG

reactuals

Version:

A useful package providing a collection of 50+ React hooks and utilities to simplify React development.

22 lines (21 loc) 709 B
import { useState, useEffect } from "react"; /** * A hook that throttles a value by a specified delay. * * Example: * const throttledValue = useThrottle(value, 500); */ export function useThrottle(value, delay) { const [throttled, setThrottled] = useState(value); const [lastExecuted, setLastExecuted] = useState(Date.now()); useEffect(() => { const handler = setTimeout(() => { if (Date.now() - lastExecuted >= delay) { setThrottled(value); setLastExecuted(Date.now()); } }, delay - (Date.now() - lastExecuted)); return () => clearTimeout(handler); }, [value, delay, lastExecuted]); return throttled; }