Home > front end >  Why is the value updated by using useState
Why is the value updated by using useState

Time:03-25

It's maybe a stupid question, but I still don't understand why is this working, I'm thinking about a while, so maybe someone can help me to get this through.

My logic: the value of the input is set to default value of the username useState hook (''). Okay, now when I type something, the changeUsername function will run (for me it is also strange, it should behave like when it is hardcoded, so the function shouldn't run at all), the username will be set to e.target.value which is ('') from the initial value of username, so why is the username updated?

I know it's a little messy what I try to explain, but I would expect that it works like when the value is hardcoded, like value='something'. Why can I still type in the input field when the value is set to ''? I hope you get it what I want to ask and understand.

const [username, setUsername] = useState('');

const changeUsername = function (e) {
    setUsername(e.target.value);
};

<input type='text' id='username' value={username} onChange={changeUsername} />

CodePudding user response:

Because...

  1. When the <input> invokes the onChange handler, it sends the new value as part of the event. The "change", if you will. (That's what's in e.target.value.) This happens on every keystroke (every change).
  2. changeUsername calls setUsername with that new value.
  3. setUsername updates state and triggers a re-render.
  4. In the re-render, username has this new state value and is set as the value of the <input>.

All of this happens very quickly (as in, faster than you can type the next character), and the re-render from React does not cause the element to lose focus.

So basically each keystroke updates the state and re-renders the entire component with the new state.

CodePudding user response:

I understand what you are trying to explain. You are saying that when the value of the input is "exemple" it will not change what ever any function is in action. The answer is easy and it is because you set the value=(useState value) and this value is always changing it is not fixed all the time,so the value of the input change when we change what is in the input. Plus,When setState is run,the code is rerendered,for exemple,you add "r" to the input,initial state will be "r" instead of "". Hope you get it.

  • Related