Lodash debounce fires on every keystroke in a React component
debounce fires on every keystroke in ReactShort answer
A debounced function keeps its timer inside itself. If your component builds a new one on every render, each call gets a fresh timer and nothing is ever delayed. Create the debounced function once with useMemo, keep the latest handler in a ref, and cancel it when the component unmounts.
Fix it fast
1Find out which cause you have
Log inside the debounced function and inside the component body. If the component logs once per keystroke and the debounced callback also logs once per keystroke, a new debounced function is being created on each render.
const debounced = debounce(() => console.log('debounced call'), 500); console.log('render');2Match what you see, then jump to its fix
- 1
The callback runs once per keystroke, only delayed by the wait timeThe debounced function is created again on every renderFix - 2
The call is delayed correctly but uses the value from an earlier renderThe debounced function reads an old prop or state valueFix - 3
A late call after navigating away, or a state update on an unmounted viewA pending call runs after the component is goneFix - 4
Nothing happens until the wait time has passed, even on the first callThe first call is expected immediately but waitsFix
- 1
What does the error look like?
debounce fires on every keystroke in Reactlodash debounce not delaying onChangedebounced function uses an old state value
Cause 1 of 4
The debounced function is created again on every render
1Check
Look for debounce(...) written directly in the component body or directly in the onChange prop. Each render then holds a different debounced function with its own timer, so calls never share one.
grep -rn "debounce(" src/2Fix
Create it once. useMemo caches the function between renders. Keep the wait time in the dependency list, nothing else.
import { useMemo } from 'react';
import debounce from 'lodash/debounce';
function Search({ onSearch }) {
const debouncedSearch = useMemo(
() => debounce((text) => onSearch(text), 500),
[onSearch]
);
return <input onChange={(e) => debouncedSearch(e.target.value)} />;
}3Verify
Type quickly. The callback should log once, about 500 ms after the last key.
console.log('search called');Confirmed by react.dev
Cause 2 of 4
The debounced function reads an old prop or state value
1Check
useMemo with an empty dependency array freezes whatever the inner function captured on the first render. Anything it reads later is stale.
grep -rn "useMemo(" src/ | grep debounce2Fix
Store the latest handler in a ref and let the debounced function call through the ref. The debounced function itself stays the same object.
import { useMemo, useRef, useEffect } from 'react';
import debounce from 'lodash/debounce';
function Search({ onSearch }) {
const latest = useRef(onSearch);
useEffect(() => { latest.current = onSearch; });
const debouncedSearch = useMemo(
() => debounce((text) => latest.current(text), 500),
[]
);
return <input onChange={(e) => debouncedSearch(e.target.value)} />;
}3Verify
Change a prop between two keystrokes. The debounced call should use the newer value.
console.log(latest.current);Confirmed by react.dev
Cause 3 of 4
A pending call runs after the component is gone
1Check
The debounced function still has a pending timer when the component unmounts.
grep -rn "debounce" src/ | grep -v cancel2Fix
Lodash gives every debounced function a cancel method. Call it in an effect cleanup. flush runs the pending call immediately if you prefer that instead.
useEffect(() => {
return () => debouncedSearch.cancel();
}, [debouncedSearch]);3Verify
Type, then navigate away within the wait time. The callback should not run.
console.log('cancelled');Confirmed by lodash.com
Cause 4 of 4
The first call is expected immediately but waits
1Check
By default debounce runs on the trailing edge only (leading is false, trailing is true), so the first call is delayed too.
grep -rn "leading" src/2Fix
Pass leading and trailing options to run on the first call, and maxWait if the call must happen at least every so often.
debounce(fn, 500, { leading: true, trailing: false });
debounce(fn, 500, { maxWait: 2000 });3Verify
The first call runs at once, or at the latest after maxWait.
console.log(Date.now());Confirmed by lodash.com
How do I stop it coming back?
- Never write debounce(...) inline in JSX. Build it once with useMemo.
- Read changing values through a ref so the debounced function does not need to be rebuilt.
- Cancel the debounced function in an effect cleanup.
- Import lodash/debounce, not the whole library, to keep the bundle small.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- TaskvareA task and project-management suite: React on the web, Flutter on mobile, TypeScript underneath.
Related fixes
Web apps
Module not found for antd/dist/antd.less after upgrading to Ant Design 5
Module not found: Error: Can't resolve 'antd/dist/antd.less'
Ant Design 5 dropped Less and the bundled CSS file for CSS-in-JS, so antd/dist/antd.less no longer exists.
3 causes, each with a fixWeb apps
Astro Code component fails inside a React component
Astro components cannot be rendered directly via function call
Astro components such as Code only exist on the server and render static HTML.
2 causes, each with a fixWeb apps
React shows Attempted import error when importing a component or function
Attempted import error:
The build found the file but not the name you asked for.
2 causes, each with a fixWeb apps
How to catch and handle a 422 from Axios in a Redux thunk
action.error.message is 'Rejected' and action.payload is undefined
A 422 means the server read the request but cannot process its content, so repeating it unchanged fails again.
4 causes, each with a fixWeb apps
axios gets 429 Too Many Requests from a React app
429 (Too Many Requests)
A 429 comes from the server or an API gateway, not from axios: your client sent too many requests in a window.
4 causes, each with a fixWeb apps
Axios request is not cancelled when a React component unmounts
A cancelled request is logged as an error in the catch block
Axios cancels a request when you pass it an AbortSignal and later call abort() on its controller.
4 causes, each with a fix