JAVASCRIPT
Throttling Function Calls with useThrottle Hook
A custom React hook `useThrottle` to limit the rate at which a function is called, improving performance for frequently triggered events.
import { useRef, useCallback, useEffect } from 'react';
function useThrottle(callback, delay) {
const throttleRef = useRef(false);
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback; // Always have the latest callback
}, [callback]);
return useCallback((...args) => {
if (!throttleRef.current) {
throttleRef.current = true;
setTimeout(() => {
callbackRef.current(...args);
throttleRef.current = false;
}, delay);
}
}, [delay]);
}
// Example Usage:
// function ScrollTracker() {
// const [scrollPos, setScrollPos] = useState(0);
//
// const handleScroll = useThrottle(() => {
// setScrollPos(window.scrollY);
// }, 200); // Update scroll position at most every 200ms
//
// useEffect(() => {
// window.addEventListener('scroll', handleScroll);
// return () => {
// window.removeEventListener('scroll', handleScroll);
// };
// }, [handleScroll]);
//
// return <p>Scroll position: {scrollPos}</p>;
// }
How it works: The `useThrottle` hook creates a throttled version of a provided `callback` function. It uses a `useRef` to keep track of whether the function is currently throttled (`throttleRef.current`). When the returned throttled function is called, it only executes the original `callback` if not currently throttled. After execution, it sets a timeout based on the `delay`, during which subsequent calls are ignored. This ensures the `callback` is called at most once within the specified `delay` period, preventing excessive function calls.