useThrottle — limit function execution frequency.
Implementation:
1import { useState, useEffect, useRef, useCallback } from "react";23function useThrottle<T>(value: T, delay: number): T {4 const [throttledValue, setThrottledValue] = useState(value);5 const lastExecTime = useRef(Date.now());67 useEffect(() => {8 const now = Date.now();9 const timeSinceLastExec = now - lastExecTime.current;1011 if (timeSinceLastExec >= delay) {12 lastExecTime.current = now;13 setThrottledValue(value);14 } else {15 const timeoutId = setTimeout(() => {16 lastExecTime.current = Date.now();17 setThrottledValue(value);18 }, delay - timeSinceLastExec);1920 return () => clearTimeout(timeoutId);21 }22 }, [value, delay]);2324 return throttledValue;25}2627// Throttled callback hook28function useThrottledCallback(callback: Function, delay: number) {29 const lastCallTime = useRef(0);3031 return useCallback((...args) => {32 const now = Date.now();33 if (now - lastCallTime.current >= delay) {34 lastCallTime.current = now;35 callback(...args);36 }37 }, [callback, delay]);38}