⚡ Fix a Debounced Handler Dropping a Keystroke
A debounce wrapper only coalesces calls into one trailing invocation if every one of those calls reaches the same function instance – the one holding the actual timer ID in its closure. A common mistake in a component-based UI is creating that wrapper fresh on every render, with no memoization at all, so each keystroke is handled by a brand-new debounce instance that has never heard of the pending timer the previous instance already scheduled. clearTimeout only works against a timer ID the current closure actually has a reference to, so each new instance quietly lets the prior instance’s own pending call continue running on its own schedule – producing one delayed call per keystroke instead of a single one at the end, with no guarantee the calls resolve in typing order once more than one is in flight.
🔎 The Problem
function SearchBox() {
const [query, setQuery] = useState('');
// Re-created on every render - this is the bug
const debouncedSearch = debounce((q) => runSearch(q), 300);
return (
<input
value={query}
onChange={(e) => {
setQuery(e.target.value);
debouncedSearch(e.target.value);
}}
/>
);
}
// Typing 'cat' fast:
// keystroke 'c' -> NEW debounce instance #1, schedules timer A
// keystroke 'ca' -> NEW debounce instance #2, schedules timer B
// (instance #2 has never seen timer A - can't clear it)
// keystroke 'cat' -> NEW debounce instance #3, schedules timer C
// All three timers (A, B, C) are independently still pending and will
// all eventually fire, each with whatever value it individually closed
// over - 'c', 'ca', and 'cat' - in whatever order the event loop
// actually resolves them, not necessarily in typing order
✅ Fix: Create the Debounced Function Once
- Create the debounced function exactly once per component instance, with useRef or useMemo, so every keystroke shares the same timer state and clearTimeout can actually cancel the previous pending call.
- Pass the latest value into the debounced call explicitly rather than relying on a closure over component state, so a shared debounce instance always acts on the most recent argument instead of whatever state existed when it was created.
- Add a cleanup that cancels any pending debounced call on unmount (most debounce utilities expose a .cancel() method) so a component that unmounts mid-wait doesn’t fire a state update against a component that’s no longer there.
🚨 Why This Is Dangerous
A search box or autosave field that occasionally loses the last character or two typed before a pause is a strange enough symptom that it’s easy to blame the network, the backend, or a flaky test rather than a debounce wrapper that was never actually debouncing more than one keystroke at a time.
A debounce function only coalesces calls it can see – and a new instance created on every render has never seen anything that came before it.




