I'm playing around with React Native and lodash's debounce.
Using the following code only make it work like a delay and not a debounce.
<Input onChangeText={(text) => { _.debounce(()=> console.log("debouncing"), 2000)() } />
I want the console to log debounce only once if I enter an input like "foo". Right now it logs "debounce" 3 times.
To use Lodash debounce in a React Native app, we can call debounce with the function we want to debounce. to assign onChangeText to a function that debounce returns which delays setText by 500 milliseconds. And then we set that as the value of the TextInput onChangeText prop.
Lodash debounce() method is that debounce function mentioned in point 3. In this case, the timer will start running from the last call of the debouncedLogHi() function. After 1500 milliseconds, the function will run.
To start using Lodash in React, you need to:Install Lodash by running npm install lodash. Import Lodash to your project by writing import _ from lodash.
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} /> } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With