ezio
ezio

Reputation: 558

Does React re-executes useState after setState?

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?

Upvotes: 2

Views: 672

Answers (2)

Tushar Shahi
Tushar Shahi

Reputation: 20701

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.

Upvotes: 2

Cristian-Florin Calina
Cristian-Florin Calina

Reputation: 1008

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

Upvotes: 3

Related Questions