To debounce input changes in React, you can follow these steps:
const debounce = (func, delay) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
func(...args);
}, delay);
};
};
const SomeComponent = () => {
const handleChange = debounce((value) => {
console.log(value);
// Do something with the debounced input value
}, 300);
const handleInputChange = (e) => {
handleChange(e.target.value);
};
return (
<div>
<input type="text" onChange={handleInputChange} />
</div>
);
};
In the example above, the handleChange function is debounced with a delay of 300 milliseconds. The handleInputChange function is called every time the input value changes, but the handleChange function is only executed after the specified delay elapsed without a new input change.
By implementing debounce in this way, you can prevent unnecessary API calls or expensive operations from being triggered on every input change, improving the performance of your React application.