Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
122
rated 0 times [  127] [ 5]  / answers: 1 / hits: 58279  / 8 Years ago, sun, december 18, 2016, 12:00:00

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.


More From » reactjs

 Answers
17

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!


[#59665] Thursday, December 15, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
odaliss

Total Points: 342
Total Questions: 102
Total Answers: 98

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
;