React Native: Using lodash debounce
Debounce function should be defined somewhere outside of render method since it has to refer to the same instance of the function every time you call it as oppose to creating a new instance like it's happening now when you put it in the onChangeText
handler function.
The most common place to define a debounce function is right on the component's object. Here's an example:
class MyComponent extends React.Component {
constructor() {
this.onChangeTextDelayed = _.debounce(this.onChangeText, 2000);
}
onChangeText(text) {
console.log("debouncing");
}
render() {
return <Input onChangeText={this.onChangeTextDelayed} />
}
}
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.
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!