JAVASCRIPT
React `useThrottle` Hook for Rate Limiting Functions
Implement a `useThrottle` hook to limit how often a function can run over time, improving performance by preventing excessive executions, especially for events like resizing or scrolling.
import { useRef, useEffect, useCallback } from 'react';
const useThrottle = (callback, delay) => {
const callbackRef = useRef(callback);
const timeoutRef = useRef(null);
const lastExecRef = useRef(0);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
const throttledCallback = useCallback((...args) => {
const now = Date.now();
const elapsed = now - lastExecRef.current;
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
if (elapsed > delay) {
lastExecRef.current = now;
callbackRef.current(...args);
} else {
timeoutRef.current = setTimeout(() => {
lastExecRef.current = Date.now();
callbackRef.current(...args);
timeoutRef.current = null;
}, delay - elapsed);
}
}, [delay]);
// Cleanup on unmount
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return throttledCallback;
};
How it works: This `useThrottle` hook creates a throttled version of a given `callback` function. It ensures that the `callback` is executed at most once within the specified `delay` period. It uses `useRef` to store the latest callback and execution timestamp, and `useCallback` to memoize the throttled function. This is crucial for performance optimization in event handlers like `onScroll` or `onMouseMove`.