Sub topic 14
Debouncing in React Without Common Pitfalls
This chapter assumes you know React function components, useState, useEffect, useMemo, and useRef. It also assumes you have read the earlier chapters on cancel and flush and on Lodash's debounce. The debouncing logic itself is the same as before. The difficulty in React comes from the render cycle. A component function runs again on every state change, so a debounced function created in the wrong place gets rebuilt each time, and its timer state is thrown away.
The Core Problem: Renders Recreate Everything
A debounced function keeps its state, the pending timer ID and the latest arguments, inside a closure. That closure exists once per call to debounce(...). If you call debounce in the body of a component, every render makes a new closure with a fresh, empty timer.
import { useState } from 'react';
import debounce from 'lodash/debounce';
// BROKEN: do not copy this pattern
function BrokenSearchBox({ onSearch }) {
const [text, setText] = useState('');
// A brand-new debounced function on every render
const debouncedSearch = debounce((query) => onSearch(query), 300);
return (
<input
value={text}
onChange={(e) => {
setText(e.target.value);
debouncedSearch(e.target.value);
}}
/>
);
}Typing "react" causes five renders. Each keystroke calls a different debounced instance, and no instance is ever called a second time to reset its timer. You get five searches, each 300 ms late. That is worse than no debounce at all.
Fix 1: Keep One Instance with useMemo
The fix is to create the debounced function once and reuse it across renders. useMemo returns the same value until one of its dependencies changes:
import { useEffect, useMemo, useState } from 'react';
import debounce from 'lodash/debounce';
function SearchBox({ onSearch }) {
const [text, setText] = useState('');
const debouncedSearch = useMemo(
() => debounce((query) => onSearch(query), 300),
[onSearch]
);
useEffect(() => {
return () => debouncedSearch.cancel();
}, [debouncedSearch]);
return (
<input
value={text}
onChange={(e) => {
setText(e.target.value);
debouncedSearch(e.target.value);
}}
/>
);
}Two details make this correct:
- The dependency array includes
onSearch. If the debounced function ignoredonSearchchanges, it would keep calling the firstonSearchit saw. That is a stale closure. - The effect cleanup calls
cancel. Without it, a timer that is pending when the component unmounts still fires and callsonSearchfor a component that no longer exists. The same cleanup runs whenonSearchchanges and the old instance is replaced, so the old instance cannot fire late with outdated logic.
You will often see useCallback(debounce(fn, 300), []). It does keep one instance, but the argument debounce(fn, 300) is still evaluated on every render and then discarded, and the empty dependency array freezes fn at its first version. useMemo with a factory function avoids both problems.
Fix 2: The Latest-Callback Ref Pattern
Often you want a debounced function that never changes identity but always calls the newest callback. A ref separates those two concerns. The debounced instance depends only on wait. The callback lives in a ref that is updated after every render.
import { useEffect, useMemo, useRef } from 'react';
import debounce from 'lodash/debounce';
export function useDebouncedCallback(callback, wait) {
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
const debounced = useMemo(
() => debounce((...args) => callbackRef.current(...args), wait),
[wait]
);
useEffect(() => {
return () => debounced.cancel();
}, [debounced]);
return debounced;
}Usage stays simple, and the parent no longer needs useCallback:
import { useState } from 'react';
import { useDebouncedCallback } from './useDebouncedCallback';
function SearchBox({ onSearch }) {
const [text, setText] = useState('');
const debouncedSearch = useDebouncedCallback((query) => onSearch(query), 300);
return (
<input
value={text}
onChange={(e) => {
setText(e.target.value);
debouncedSearch(e.target.value);
}}
/>
);
}The ref is updated inside an effect and not during render, because React expects render to be free of side effects. Timers set by the debounce always fire after the commit phase has finished, so the ref already holds the latest callback by the time it is read.
Fix 3: Debounce the Value Instead of the Callback
Sometimes nothing needs to be called. You only want a value that settles. A debounced-value hook needs no library:
import { useEffect, useState } from 'react';
export function useDebouncedValue(value, wait) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), wait);
return () => clearTimeout(id);
}, [value, wait]);
return debounced;
}Every change to value runs the effect again. React first runs the previous cleanup, which clears the old timer. This is the trailing-edge debounce from earlier chapters, with React's effect cleanup acting as clearTimeout.ook works well with data fetching. Debouncing cuts the number of requests, but responses can still arrive out of order. An AbortController in the same effect cancels the request that is now stale:
import { useEffect, useState } from 'react';
import { useDebouncedValue } from './useDebouncedValue';
function SearchResults({ query }) {
const debouncedQuery = useDebouncedValue(query, 300);
const [items, setItems] = useState([]);
useEffect(() => {
if (!debouncedQuery) {
setItems([]);
return;
}
const controller = new AbortController();
fetch(`/api/search?q=${encodeURIComponent(debouncedQuery)}`, {
signal: controller.signal,
})
.then((res) => res.json())
.then((data) => setItems(data))
.catch((err) => {
if (err.name !== 'AbortError') console.error(err);
});
return () => controller.abort();
}, [debouncedQuery]);
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}Debounce decides when a request starts. Abort makes sure only the latest request can update state. You need both.
Pitfalls Around the Edges
Debouncing the state update itself
Never debounce setText on a controlled input. React re-renders the input with the old value until state updates, so the field appears frozen and can drop keystrokes. Update local state right away and debounce only the expensive work, such as a search, a save, or validation.
Passing the event object
Pass e.target.value and not e. React 17 removed event pooling, so the event object no longer gets wiped. But properties such as currentTarget are only meaningful during dispatch, and by the time a debounced call runs 300 ms later, they no longer point where you expect. Extracting plain data before the call avoids this entirely.
StrictMode double effects
In development, StrictMode mounts, unmounts, and remounts each component, so your cleanup runs once right away. With useMemo, the debounced instance survives. cancel clears pending work but leaves the function usable, so the remount works. Avoid a custom "disposed" flag that permanently disables the function in cleanup. It would break under StrictMode and under Fast Refresh.
Flushing on unmount instead of cancelling
Cancel is right for searches, because nobody needs results after leaving. For autosave, losing the last edit is a bug. Call flush() in cleanup instead, so the pending save runs immediately:
useEffect(() => {
return () => debouncedSave.flush();
}, [debouncedSave]);| Symptom | Likely cause | Fix |
|---|---|---|
| Every keystroke fires, just delayed | `debounce` called in render body | `useMemo` or `useDebouncedCallback` |
| Debounced call uses old props or state | Empty deps freeze the first callback | Add deps, or use the ref pattern |
| Call never fires while parent re-renders | Unstable callback recreates the instance | `useCallback` in parent, or ref pattern |
| Warning or work after navigation | No cleanup on unmount | `cancel()` in effect cleanup |
| Last autosave edit is lost | `cancel()` used where `flush()` was needed | `flush()` in cleanup |
| Input lags or drops characters | Debouncing the state setter | Update state immediately, debounce side effects |
| Old results overwrite new ones | Responses arrive out of order | `AbortController` in the fetch effect |
Exercise
A teammate writes const save = useMemo(() => debounce(() => api.save(form), 1000), []); where form is component state. Saves run on schedule but always send the original empty form. Explain why, and give two ways to fix it.
Show answer
The empty dependency array makes useMemo build the debounced function once, during the first render, so its inner closure captures the first form value forever. Fix 1: pass the data as an argument, debounce((data) => api.save(data), 1000), and call save(form). Fix 2: keep form in a ref updated in an effect, or use the useDebouncedCallback hook, so the stable debounced function reads the latest value when it fires. Adding form to the deps is the wrong fix: the instance would be rebuilt on every edit and the cleanup would cancel each pending save.
Exercise
Why does useDebouncedValue need no cancel method or separate unmount effect, while the useMemo approach does?
Show answer
Its timer is created inside a useEffect whose cleanup clears it. React runs that cleanup both before the effect runs again (on a value change) and on unmount, so resetting and cancelling come from React's effect lifecycle. With useMemo, the timer lives inside a Lodash closure that React knows nothing about, so you must add an effect that calls cancel() or flush() yourself.
Exercise
In a search component using useDebouncedValue(query, 300), the user types "cat", pauses 400 ms, then types "s". The "cat" request takes 800 ms and the "cats" request takes 100 ms. Without an AbortController, what does the user see at the end? With one?
Show answer
Without abort, "cats" results arrive first and render, then the slow "cat" response arrives and overwrites them, leaving stale results on screen. With abort, the change of debouncedQuery to "cats" runs the previous effect's cleanup, which aborts the "cat" request. Its promise rejects with AbortError, which is ignored, so only "cats" results are shown.