Perform debounce in React.js

前端 未结 30 1936
礼貌的吻别
礼貌的吻别 2020-11-22 04:11

How do you perform debounce in React.js?

I want to debounce the handleOnChange.

I tried with debounce(this.handleOnChange, 200) but it doesn\'t

30条回答
  •  独厮守ぢ
    2020-11-22 04:47

    You can use Lodash debounce https://lodash.com/docs/4.17.5#debounce method. It is simple and effective.

    import * as lodash from lodash;
    
    const update = (input) => {
        // Update the input here.
        console.log(`Input ${input}`);     
    }
    
    const debounceHandleUpdate = lodash.debounce((input) => update(input), 200, {maxWait: 200});
    
    doHandleChange() {
       debounceHandleUpdate(input);
    }
    

    You can also cancel the debounce method by using the below method.

    this.debounceHandleUpdate.cancel();
    

    Hope it helps you. Cheers!!

提交回复
热议问题