Debouncing input handlers in React
This post is about debouncing, i.e. intentionally postponing what happens when a user interacts with inputs.
The topic of this post is debouncing - put differently, intentionally postponing what happens as a result of a user interacting with inputs.
Event handling
In React (and in JavaScript more broadly), input changes are typically processed with some form of event listener, for example onChange callbacks. Take a plain, old text input: each keystroke triggers the attached handler and passes it an event object that carries the most recent value.
const handler = (event: React.ChangeEvent<HTMLInputElement>) => {
/*..*/
};
/*..*/
<input onChange={handler} />;
This works nicely for keeping the app state synchronized, but is it what we want every time? Does every single tiny change really have to cause an effect, no matter the situation?
Use case
Suppose you have to build a text search component for your app, where the user enters the search query into a simple input. To improve the UX, you drop the “submit” button and instead pass the query on to the API while the user is still typing. Modern UIs commonly work this way.
Everything is fine until you notice that each keystroke makes the browser send an XHR (HTTP) request to the backend. Multiply that by the number of people using your app at the same moment, and there you go – you have unintentionally created something that resembles a DDoS (distributed denial of service) attack. In the best case - once the server gets “flooded” with hundreds of requests within a fairly short period, IDS/IPS protection mechanisms would blacklist some of the clients’ IPs. In the worst case - the whole backend service crashes.
❗️ On top of that, firing so many asynchronous requests within a short period significantly raises the chance that the responses will arrive in the wrong order.
For the user, this race condition causes highly irritating UI inconsistencies, e.g. an older request resolving last, so the UI ends up showing results for a stale version of the query.
Non-debounced effects
The animation below illustrates the “flood” of events coming from an input without debouncing:
Every keystroke is processed individually. The “debugger” window records each “effect”, imitating the queries that might be sent to the backend server. This is obviously far from optimal.
Proper event handling
Here, I am using lodash.debounce (essentially a standalone function pulled out of the “parent” lodash library) to build a debounced variant of the event handler:
import debounce from "lodash.debounce";
const DEBOUNCE_TIME_MS = 300;
/*..*/
const onNameChange = useMemo(
() =>
debounce((event: React.ChangeEvent<HTMLInputElement>) => {
setEffects(/*..*/);
}, DEBOUNCE_TIME_MS),
[]
);
In this code, debounce takes two arguments: the function (handler) and the wait time.
ℹ️ Strictly speaking,
debouncetakes a third argument as well,options, which lets you define e.g. whether the handler should fire at the leading and/or trailing edge of the timeout. It is optional, though, and can be omitted.
On top of that, everything is wrapped in React’s useMemo hook so that the function is not needlessly recreated on each render.
The animation below demonstrates how the debounced event handler behaves.
The difference is easy to notice: while the user kept typing (with a “gap” between keystrokes shorter that DEBOUNCE_TIME_MS), the effect was postponed.
Notice how the user paused twice for a moment while typing, close to the end of the sentence (and a third time - once they were done)? Those are the moments when the debounced effects fired. The debugger recorded just 3 effects, a huge improvement compared to about 13x more events in the version without debouncing!
ℹ️ Keep in mind - a debounced event handler works more or less like this:
- capture user-generated events and “collect” them;
- wait until a period of “silence” (no events) passes, typically about 300-500 milliseconds;
- run the effect using the “most recent” payload.
Cleaning up
It is also a good idea to provide clean-up logic in case the component unmounts (for instance, when the user leaves the route). That is why you should add a useEffect that returns a function calling the .cancel() method of the debounced event handler.
useEffect(() => {
return () => {
onNameChange.cancel();
};
}, [onNameChange]);
💡 The reason: suppose
DEBOUNCE_TIME_MSis long enough (eg. 1000-2000ms) for the following to happen:
- the user begins typing;
- the user right away leaves the current route, so the search component unmounts before the debounced effect runs
In this hypothetical case, you could end up with a memory leak – more precisely, an attempt to update the state of a component that has already been unmounted. This is why it is good practice to always clear any scheduled tasks that we know would not be handled properly.
Each function returned from calling
debounce(..)comes with a few extra properties, which is why.cancel()can be called on it.
Take away notes
To deliver an excellent user experience, modern interfaces need to consider performance. Optimizing how events and effects are handled is just one of the many things engineers must keep in mind.
That does not mean you have to “fix” every input in each of your apps - for instance, it is perfectly fine for an ordinary text input to update the form’s in-memory state on each keystroke. Always consider what handling events at different frequencies will cause, and pick the strategy that suits the situation.
ℹ️ If you are curious, here you will find a working example of a debounced event handler together with the complete codebase.