Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update a form's input text state immediately in React using setState()

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading