Debounce text input in React

Jacob Do
Nov 6, 2020

Picture the scenario — you want to make a request to your API every time the user enters a value in an input and you do not want them to have to press a button every time they want to trigger search.

Instead, you wish to make the request when the user stops typing, but not on each keypress so that there is not an undue strain on the API and also user is not presented with a flickering result list.

The requirements for the solution are as follows:

  • Controlled input is used
  • Search request is only made when user stops typing

First of, we start with a good old fashioned controlled input:

An easy way to implement debounce logic is to use the debounce function provided by the highly popular utility library https://lodash.com/.

Run the following command to install it in your project:

npm i lodash

Next, we want to set up our debounce function. The logic should be placed outside of the component and only invoked within the component as the inputValue changes, otherwise the debounce function will be re-built on each render and will not work.

Here the function search is placed outside of the component and now it will be properly debounced — it will be invoked with the latest value of inputValue 500 milliseconds after the latest change of the state variable.

Working code for this is available here:

https://codesandbox.io/s/debounce-input-in-react-tci4q

--

--

Jacob Do

HTML engineer by day, Meme connoisseur by night