Debounce onChange

Viewed 1080

I have a Material UI Textfield that contains an onChange. This onChange, takes the event and execute the function handleOnChange. With this current implementation, the function handleOnChange is executed every-time the event changes.

It it possible to use debounce to execute the function only after 2000ms directly on the event?

My textfield

<TextField
  onChange={
    event =>
      handleOnChange(
      event.target.value,
      firstValue,
      secondValue,                            
    )
/>

My function

const handleOnChange = (value, firstValue, secondValue) => {
  ...do something..
}

I tried the following, but handleOnChange still fires at every event change, not after 2000ms.

<TextField
  onChange={
    event =>
      _.debounce(handleOnChange(
      event.target.value,
      firstValue,
      secondValue,                            
    ), 2000)
/>
2 Answers

You are creating a debounced instance on every event call. Try creating one instance of debounced function and use it in your handler. Something like this:

const handleOnChange = _.debounce(change => {
  console.log(change);
}, 1000);

export default function App() {
  return (
    <div className="App">
      <input onChange={event => handleOnChange(event.target.value)} />
    </div>
  );
}

The issue is that you are passing the result of the handleOnChange() function to debounce, rather than a reference to the function.

Try something more like this:

<TextField
  onChange={
    event =>
      _.debounce(() => handleOnChange(
          event.target.value,
          firstValue,
          secondValue,                            
        ), 2000)
/>
Related