I need the state to change to maintain the string the user is typing. However I want to delay an action until the user stops typing. But I can't quite place my finger on how to do both.
So When the user stops typing I want an action to be triggered, but not before. Any suggestions?
To keep the string the user is typing, use the useState hook to store the text the user is typing. Then give that state to the value of the input. Also be sure to use setState on the onChange event handler of the input, otherwise the input value won't change.
Solution. To avoid that problem, we better execute a function in proper timing which means after a user stops typing for a while. And setTimeout helps us to do that. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
Onchange in React input causes the input to rerender on every letter.
How to use setTimeout in React. The setTimeout function accepts two arguments: the first is the callback function that we want to execute, and the second specifies the timeout in milliseconds before the function will be called. setTimeout(() => console. log('Initial timeout!'
To keep the string the user is typing, use the useState
hook to store the text the user is typing. Then give that state to the value of the input. Also be sure to use setState
on the onChange
event handler of the input, otherwise the input value won't change.
To trigger an action only sometime after the user stops typing, you can use the useEffect
hook together with setTimeout
. In this case, we want to trigger useEffect
when the input value changes, so we'll create a useEffect
hook and on its dependency array give it the variable with the value of the input. The function given to useEffect
should use setTimeout
to trigger an action after the delay time that is desired. Also, the function given to useEffect
should return a cleanup function that clears the timeout set. This avoids doing actions for input values which are no longer relevant to the user.
Below is a little example of an app that uses the above steps to keep the string the user is typing visible and to show the finished string 500ms after the user stops typing.
function App() { const [query, setQuery] = useState(""); const [displayMessage, setDisplayMessage] = useState(""); useEffect(() => { const timeOutId = setTimeout(() => setDisplayMessage(query), 500); return () => clearTimeout(timeOutId); }, [query]); return ( <> <input type="text" value={query} onChange={event => setQuery(event.target.value)} /> <p>{displayMessage}</p> </> ); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With