How to make React input onChange set state only after onChange stops firing for set time?
You don't really need a ref to solve this. A call touseEffect
should be enough:
useEffect(() => { const timeout = setTimeout(() => { setOutput(userValue); }, 600); return () => { clearTimeout(timeout); };}, [userValue]);const updateOutput = (e) => { setUserValue(e.target.value);};
You can try this way
const updateOutput = () => {setUserValue(inputRef.current.value);setTimeout(() => {setOutput(inputRef.current.value)}, 700) }
Hope this will help you.
This ought to do the trick. You'll want to use a ref
to persist the debounced function across repaints:
const { useCallback, useState, useRef } = React;const { render } = ReactDOM;const { debounce } = _;function App() { const [userValue, setUserValue] = useState(0); const [output, setOutput] = useState(0); const debounced = useRef(debounce((value) => setOutput(value), 600)) const updateUserValue = useCallback(({ target: { value }}) => { setUserValue(value); debounced.current(value) }, []); return ( <div className="App"> <div> <h1>Input</h1> <input value={userValue} type="number" onChange={updateUserValue} ></input> </div> <div> <h1>Output</h1> {output} </div> </div> );}render(<App />, document.body);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script><script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>