Perform debounce in React.js

前端 未结 30 1562
礼貌的吻别
礼貌的吻别 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:37

    2019: Use the 'useCallback' react hook

    After trying many different approaches, I found using useCallback to be the simplest and most efficient at solving the multiple calls problem of using debounce within an onChange event.

    As per the Hooks API documentation,

    useCallback returns a memorized version of the callback that only changes if one of the dependencies has changed.

    Passing an empty array as a dependency makes sure the callback is called only once. Here's a simple implementation :

    import React, { useCallback } from "react";
    import { debounce } from "lodash";
    
    const handler = useCallback(debounce(someFunction, 2000), []);
    
    const onChange = (event) => {
        // perform any event related action here
    
        handler();
     };
    

    Hope this helps!

提交回复
热议问题