Home > Software engineering >  Does React re-executes useState after setState?
Does React re-executes useState after setState?

Time:06-27

If setState trigger a re-rendering of the component, and useState executes for every render, then why does it updates the old value if the initialization is going to be re-executed?

for example, if i have a counter set to 0 (useState(0)) and i modify the state of that counter via setState to 1, that will trigger a re-render therefore useState will be executed again and therefore the value should be zero again, but that does not happen(fortunately) and i don't know why?

CodePudding user response:

That's how this react hook is implemented.

The value parameter is ignored on subsequent renders by react. It will only be set to this value on the initial render.

You can read more about the internals of React from authors that went inside the code to check it or check the internal code yourself.

Here's one that I've found: https://www.newline.co/@CarlMungazi/a-journey-through-the-usestate-hook--a4983397

CodePudding user response:

useState is triggered on every render yes. But the value is disregarded after the very first render.

From the docs:

You might be wondering: why is useState not named createState instead? “Create” wouldn’t be quite accurate because the state is only created the first time our component renders. During the next renders, useState gives us the current state.

  • Related