DEV Community

Kuldeep Bora
Kuldeep Bora

Posted on

Debouncing (lodash) with React

Scenario: Getting something done on input change is not efficient in scenario where that 'something' is to fetch data from an api or to call another prop function or state action.

Solution: One of the solution is to use debounce/throttle api. There are several libraries which allows us to do just that. Lodash is one of them.

import { debounce, throttle } from 'lodash';

Code: Functional component

const delayedHandleChange = debounce(eventData => someApiFunction(eventData), 500);

const handleChange = (e) => {
        let eventData = { id: e.id, target: e.target };
        delayedHandleChange(eventData);
    }

Above handleChange() function will be used in our react input component for onChange props.

For class component, we have to bind functions like so:

constructor(props) {
this.throttleHandleChange = debounce(this.throttleHandleChange.bind(this), 500);
this.handleChange = this.handleChange.bind(this);

}

throttleHandleChange(edata) {
   someApiFunction(edata);
}

handleChange(e) {
    let edata = { id: e.id, target: e.target }
    this.throttleHandleChange(edata)
};

Same as above, handleChange gets called on our input component.
This allows us to only call api function once user has stopped typing for 500ms or more.

Throttle api can be used in exact same way. Only difference is that throttle allows us to call api once every 500ms (above example) while typing.

Hope this helps. Thanks and happy coding. :)

Top comments (2)

Collapse
 
all43 profile image
Evgenii Malikov

You're missing important point - debounced function should be declared outside of functional component or with use of useMemo/useCallback hooks. Otherwise it will be overwritten on every component re-render

Collapse
 
ryskin profile image
Alexey

This comment saved me time!