React Use Debounce With Setstate
Background Assume we all know about the debounce function from lodash. If a user quickly input 1,12,123,1234, it allows us to proceed an alert only once, with 1234, after a certain
Solution 1:
Try this (using useCallback):
importReact, { useState, useCallback } from"react";
import"./styles.css";
import { debounce } from"lodash";
const request = debounce(value => {
alert(`request: ${value}`);
}, 1000);
exportdefaultfunctionApp() {
const [input, setInput] = useState("");
const debouceRequest = useCallback(value =>request(value), []);
constonChange = e => {
debouceRequest(e.target.value);
setInput(e.target.value); // Remove this line will lead to normal denounce
};
return (
<divclassName="App"><inputonChange={onChange} /></div>
);
}
Post a Comment for "React Use Debounce With Setstate"