Lodash debounce not working in React

前端 未结 3 1131
别那么骄傲
别那么骄傲 2021-02-05 04:09

it would be best to first look at my code:

import React, { Component } from \'react\';
import _ from \'lodash\';
import Services from \'Services\'; // Webser         


        
3条回答
  •  时光说笑
    2021-02-05 04:22

    For a React functional component, debounce does not work by default. You will have to do the following for it to work:

    const debouncedFunction= React.useCallback(debounce(functionToCall, 400), []);
    

    useCallback makes use of the function returned by debounce and works as expected. Although, this is a bit more complicated when you want to use state variables inside the debounced function (Which is usually the case).

    React.useCallback(debounce(fn, timeInMs), [])
    

    The second argument for React.useCallback is for dependencies. If you would like to use a state or prop variable in the debounced function, by default, it uses an an old version of the state variable which will cause your function to use the historical value of the variable which is not what you need. To solve this issue, you will have to include the state variable like you do in React.useEffect like this:

    React.useCallback(debounce(fn, timeInMs), [stateVariable1, stateVariable2])
    

    This implementation might solve your purpose. But you will notice that the debounced function is called every time the state variables (stateVariable1, stateVariable2) passed as dependencies change. Which might not be what you need especially if using a controlled component like an input field.

    The best solution I realized is to put some time to change the functional component to a class based component and use the following implementation:

    constructor(props)
        {
            super();
            this.state = {...};
            this.functionToCall= debounce(this.functionToCall.bind(this), 400, {'leading': true});
        }
    

提交回复
热议问题