Sub topic 14
Debouncing in React Without Common Pitfalls
This chapter assumes you know React function components, the useState, useMemo, useEffect, and useRef hooks, and the Lodash debounce function with its cancel method from the previous chapter.
A debounced function only works if every call reaches the same instance. Each instance owns one timer, and a call can only reset that instance's own timer. React makes this easy to get wrong, because a component's body runs again on every render.
Pitfall 1: Creating the Debounced Function During Render
This version looks reasonable but does not debounce at all:
import { useState } from 'react';
import debounce from 'lodash/debounce';
function BrokenSearchBox({ onSearch }) {
const [text, setText] = useState('');
// A new debounced function is created on every render
const debouncedSearch = debounce((query) => onSearch(query), 300);
return (
<input
value={text}
onChange={(e) => {
setText(e.target.value);
debouncedSearch(e.target.value);
}}
/>
);
}Each keystroke calls setText, which triggers a re-render, and the re-render creates a fresh debounced function. Every instance receives exactly one call, so each one fires 300 ms later. Typing "react" sends five searches, each 300 ms late.
The Fix: A Stable Instance Plus Cleanup
useMemo keeps one debounced function across renders. An effect cleanup cancels any pending call when the component unmounts. Without that cleanup, a late call could update state in an unmounted component or send a request nobody needs.
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);
}}
/>
);
}The cleanup also runs when onSearch changes and useMemo builds a new instance, so the old instance's timer never fires.
Pitfall 2: An Unstable Callback Prop
useMemo only helps if its dependencies stay the same. If the parent writes <SearchBox onSearch={(q) => fetchResults(q)} />, then onSearch is a new function on every parent render. The memo rebuilds, the cleanup cancels the pending call, and the search may never run.
You can fix it in two ways:
| Approach | How it works | Trade-off |
|---|---|---|
| `useCallback` in the parent | Keeps `onSearch` stable | Every caller has to remember to do it |
| Ref to latest callback | The debounced function reads `ref.current` when it fires | Takes a little more code, but callers need no special care |
The ref approach fits naturally into a reusable hook:
import { useEffect, useMemo, useRef } from 'react';
import debounce from 'lodash/debounce';
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;
}The debounced instance now depends only on wait. It always calls the newest callback, so it also avoids stale closures, where a function keeps using props or state from an old render.
Exercise
A component defines const save = useMemo(() => debounce(() => persist(draft), 1000), []); and calls save() on every change. The saved value is always the empty initial draft. Why, and how do you fix it?
Show answer
The empty dependency array means the debounced function captures draft from the first render, which is a stale closure. Fix it by passing the value as an argument, as in debounce((value) => persist(value), 1000) called with save(draft), or by reading the latest value from a ref, as useDebouncedCallback does.
Exercise
Why does the SearchBox effect list debouncedSearch as a dependency instead of using an empty array?
Show answer
When onSearch changes, useMemo creates a new instance. Listing debouncedSearch makes the cleanup cancel the old instance's pending call, and the effect then registers cleanup for the new instance. With an empty array, only the last instance would be cancelled on unmount.