const [text, setText] = useState('');
const handleTextChange = (e) => {
setText(e.target.value);
}
// Inside a form
<input onChange={handleTextChange} value={text} type="text" />
I’m trying to do something very simple but can’t quite get it to work properly. From the code above, I have text and setText to store and update the state, and a function handleTextChange which gets called by the input field’s onChange method.
I know that setState() is async so wont update immediately, however, If i need access to the updated result immediately how can I get it? I’ve read that useEffect hook can be used to do this but I can’t figure out how I need to use it. If there is another way to accomplish this then please share.
The main objective is to get the "updated value of the text state variable" as the user is typing in the input field.
>Solution :
yep you are right you need to use useEffect
you just need something like this
useEffect(()=>{
// do something with updated value
},[text])
this useEffect will have the updated value of text…basically it will run everytime setText is called and it sees an updated value for the text
Edit: or as comment suggested you can always use e.target.value for the latest value unless you really want to use state variable
you can use disabled={text.length===10}
credit to https://stackoverflow.com/users/633183/mulan