JAVASCRIPT
Throttle Function Calls for Performance with useThrottle Hook
Build a custom useThrottle React hook to limit how often a function can run, optimizing performance for rapidly firing events like scrolling or window resizing.
import { useState, useEffect, useCallback, useRef } from 'react';
function useThrottle(value, limit) {
const [throttledValue, setThrottledValue] = useState(value);
const lastRan = useRef(Date.now());
const timeoutRef = useRef(null);
const throttleFunction = useCallback(() => {
if (Date.now() - lastRan.current >= limit) {
setThrottledValue(value);
lastRan.current = Date.now();
} else {
clearTimeout(timeoutRef.current);
timeoutRef.current = setTimeout(() => {
setThrottledValue(value);
lastRan.current = Date.now();
}, limit - (Date.now() - lastRan.current));
}
}, [value, limit]);
useEffect(() => {
throttleFunction();
return () => clearTimeout(timeoutRef.current);
}, [value, limit, throttleFunction]);
return throttledValue;
}
// Example Usage:
// function MyThrottledComponent() {
// const [searchTerm, setSearchTerm] = useState('');
// const throttledSearchTerm = useThrottle(searchTerm, 500); // Update every 500ms
//
// useEffect(() => {
// if (throttledSearchTerm) {
// console.log('Fetching data for:', throttledSearchTerm);
// // Perform API call with throttledSearchTerm
// }
// }, [throttledSearchTerm]);
//
// return (
// <input
// type="text"
// placeholder="Type to search (throttled)"
// value={searchTerm}
// onChange={(e) => setSearchTerm(e.target.value)}
// />
// );
// }
How it works: The `useThrottle` hook limits how often a function can execute, ensuring it runs at most once within a specified time window (`limit`). Unlike debouncing, which waits for a pause before executing, throttling guarantees regular execution at a controlled rate. This is crucial for optimizing performance in scenarios with high-frequency events like scrolling, resizing, or rapid input, preventing excessive re-renders or API calls.