Hint
Debouncing in React: useEffect with a setTimeout + cleanup. The cleanup clears the pending timeout when the value changes, so only the final value triggers the actual search.
function debounce(fn, delay) {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
const searchLog = [];
let searchCallCount = 0;
const search = debounce((query) => {
searchCallCount++;
searchLog.push('search:' + query);
}, 50);
// Simulate fast typing
['r', 're', 'rea', 'reac', 'react'].forEach((q, i) => {
setTimeout(() => search(q), i * 10); // 10ms apart, debounce is 50ms
});
// After all typing stops (5 * 10 = 50ms) + 50ms debounce = 100ms
setTimeout(() => {
console.log(searchCallCount);
console.log(searchLog[0]);
}, 150);1 search:react
Explanation: Each keystroke resets the 50ms timer. Only the last keystroke ('react' at 40ms) fires — its timer completes at 90ms with no further input.
Key Insight: Debouncing in React: useEffect with a setTimeout + cleanup. The cleanup clears the pending timeout when the value changes, so only the final value triggers the actual search.