Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debounce onChange

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)
/>
like image 856
Magofoco Avatar asked Aug 03 '26 14:08

Magofoco


1 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>
  );
}
like image 113
tjankowski Avatar answered Aug 07 '26 10:08

tjankowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!