I am trying to debounce an input. I have memoized the debounce handler so that it does not change references on each render. I need the input to be bound to a state value as I need to set it elsewhere in my app. The issue is that the input value is never able to be updated as when inside the debounced changeHandler e.target.value always contains previous value, not a new value entered. How can i debounce the input that is bound to a state value?
xport function App() {
const [query, setQuery] = useState("a value");
const changeHandler = (event) => {
console.log(event.target.value); // wrong value
setQuery(event.target.value);
};
const debouncedChangeHandler = useCallback(debounce(changeHandler, 1000), []);
return (
<div>
<input
value={query}
onChange={debouncedChangeHandler}
type="text"
placeholder="Type a query..."
/>
</div>
);
}
sandbox: https://codesandbox.io/s/react-debounce-5pidiy?file=/src/index.js:130-596