Home > Software engineering >  Getting ambiguous output from useState()
Getting ambiguous output from useState()

Time:08-22

I was playing around with React lifecycle methods using hooks, and I got something unexpected, I made a button that will change the state name to 'amritesh', but after changing the name from an empty string to 'amritesh', I will again be able to change it from 'amritesh' to 'amritesh' and that is not how virtual DOM works in react, as per my knowledge.

How was I able to know that it was changing again?

By clicking twice on the button, the console prints 'hi' and 'amritesh' again, but it only prints twice after that it won't work.

Now, the question arises if it changes the same name second time why not for the third time, fourth time, and so on?

Codesandbox link -> https://codesandbox.io/s/silly-jones-p1eeuz?file=/src/App.js

CodePudding user response:

Placing console.logs should usually be done inside useEffect. The reason is, that a component might not re-render, might recalculate only the return statement, etc.

It is also true that if the new state strictly equals the previous one, it won't re render. Strings are primitives, so:

'amritesh' === 'amritesh' // true

But

{d: 3} === {d: 3} // false, different objects in memory, thus re render.

In your case, React detects that the previous state equals the new one, and doesn't re-render.

Your name gets printed twice because React needs to compare twice the states. But from the second time, it doesn't re-render.

  • Related