DEV Community

Kuldeep Bora
Kuldeep Bora

Posted on

9 4

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. :)

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

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!

Sentry image

Make it make sense

Make sense of fixing your code with straight-forward application monitoring.

Start debugging →

👋 Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple “thank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay