JAVASCRIPT
React useThrottle Hook for Limiting Function Calls
Implement a custom `useThrottle` React hook to limit how often a function can execute, improving performance for events like scrolling or resizing.
import { useRef, useCallback } from 'react';
function useThrottle(callback, delay) {
const throttleRef = useRef(false);
const timeoutRef = useRef(null);
const throttledCallback = useCallback((...args) => {
if (!throttleRef.current) {
callback(...args);
throttleRef.current = true;
timeoutRef.current = setTimeout(() => {
throttleRef.current = false;
}, delay);
}
}, [callback, delay]);
return throttledCallback;
}
How it works: The `useThrottle` hook ensures a function (callback) is called at most once within a specified `delay` period. It uses `useRef` to track if the function is currently throttled and `setTimeout` to reset the throttle state. The `useCallback` hook memoizes the throttled function, preventing unnecessary re-creations. This is essential for performance optimization of frequently triggered events like window resizing or continuous user input.