actually, I am new to React and I am trying to put debouncing along with the event method(onChange) in input to make the code optimized, but when the event occurs instead of calling the function for one time it calls several times(up to infinity).
import { useRef } from "react";
import "./styles.css";
export default function App() {
var input_ref = useRef(null)
//.............Debouncing........................................................
var debouncing = (callback,threshold)=>{
var timer;
return function(){
const context = this
if(timer)clearTimeout(timer);
timer = setInterval(()=>{
timer = null;
callback.apply(context);
//callback()
},threshold);
}
}
//........EventHandler with Debouncing............................................
var search_data = debouncing(()=>{
console.log(input_ref.current.value)
},300)
return (
<div className="App">
<input type="text" name='searchBox' placeholder="search" ref={input_ref} onChange={search_data}/>
</div>
);
}
link (CodeSandbox):- https://codesandbox.io/s/debouncing-testing-gxc031?file=/src/App.js