1

I have a range UI component. A user can drag the MIN/MAX range UI component and the callback might be called a bunch of time in one second. However, each change will involve remote API call.

Is there any best practice to improve this? Thanks

handlePingRange(data){
    this.props.updateFilter("minPing", data[0])
    this.props.updateFilter("maxPing", data[1])
}



<div className="form-group col-md-4">
    <Range allowCross={false} value={this.state.pingRangeValues} step={5}  className="form-control-range"  onChange={this.handlePingRange.bind(this)} />
</div>
Jee Mok
  • 6,157
  • 8
  • 47
  • 80
newBike
  • 14,385
  • 29
  • 109
  • 192
  • 1
    Possible duplicate of [Perform debounce in React.js](https://stackoverflow.com/questions/23123138/perform-debounce-in-react-js) – Danny Buonocore Sep 29 '19 at 02:28

2 Answers2

3

Consider throttling or debouncing. Both are implemented in lodash helper library. You can use it with React.

Throttling enforces a maximum number of times a function can be called over time. E.g. "execute this function at most once every 100 milliseconds."

Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. E.g. "execute this function only if 100 milliseconds have passed without it being called."

const throttledHandlePingRange = _.throttle(handlePingRange 100);
const debouncedHandlePingRange = _.debounce(handlePingRange, 100);

If using lodash is not an option you can implement it yourself:

function debounce(fn, delay) {
    let timer = null;
    // closure function that has access to timer
    return function() {
      // get the scope and parameters of the funct via 'this' and 'arguments'
      let that = this;
      let args = arguments;
      // if event is called, clear the timer and start over
      clearTimeout(timer);
      timer = setTimeout(function() {
           fn.apply(that, args);
      }, delay);
  }
}
winwiz1
  • 2,906
  • 11
  • 24
1

I would rather use onBlur than use onChange for handling changing the range, i.e. if the minnimal-icon on the component range is still onFocus and the user is trying to change the min value, the API will not be triggered; but if the user leave the minimal-icon, the API will be triggered onBlur.

vikbert
  • 1,128
  • 11
  • 10