Debounced value hook with max wait and flush controls
A product search box should not fetch on every keystroke. It should fetch when the user pauses. But a fast typist who never pauses should still see results now and then, and pressing Enter should search right away. Implement a React hook, useDebouncedValue, that returns a debounced copy of a value with these controls.
function useDebouncedValue<T>(
value: T,
delay: number,
options?: { maxWait?: number },
): {
debounced: T;
pending: boolean;
flush: () => void;
}
debounced is value right away.value changes, debounced keeps its old value until value has not changed for delay ms. Then it becomes the latest value. Intermediate values are skipped.pending is true while value differs from debounced (compare with Object.is), and false otherwise.value changes back to the current debounced value before the delay is over, nothing is waiting anymore: pending is false and the timer is cleared.options.maxWait (optional): while value keeps changing, debounced must update no later than maxWait ms after the first change of the burst, to the value at that moment. The next change after that update starts a new burst.flush() sets debounced to the latest value right away and clears the timer. If nothing is pending, it does nothing. flush keeps the same identity across renders.function ProductSearch() {
const [query, setQuery] = useState('');
const { debounced, pending, flush } = useDebouncedValue(query, 300, { maxWait: 1000 });
useEffect(() => { if (debounced) api.search(debounced); }, [debounced]);
return (
<form onSubmit={(e) => { e.preventDefault(); flush(); }}>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
{pending && <span>Typing…</span>}
</form>
);
}
// delay 300
// t = 0 value 'l' debounced '' pending true
// t = 100 value 'la' debounced ''
// t = 200 value 'lam' debounced ''
// t = 500 debounced 'lam' pending false ('l' and 'la' are skipped)
// delay 300, maxWait 1000, a change every 200 ms starting at t = 0
// t = 1000 debounced = the value at t = 1000, even though typing continues
value and calls to flush happen inside ReactDOM.flushSync. Some tests record every debounced value that was committed.setTimeout, clearTimeout, setInterval, clearInterval, Date.now and performance.now with a fake clock and move it forward by exact amounts. Some tests count the timers that are still pending.Object.assign(window, { useDebouncedValue }); below “Do not edit below this line”. The tests use it to call your hook.