How does react updates counter variable when used in useState hook
Can someone explain why this implementation only increments the button once, even though increment was called twice?
Also, notice that
counter
is a const, right? How come this value is updated each time we click our component? I'm a bit confused. What is happening under the hood?10 Replies
(1) It's constant throughout each execution of the function. The first time it's rendered it's a constant 0, the second time a constant 1, etc. const means it can't be set to something else later on in that scope, not that it's the same every time the function is called
yeah I see, when the component is first rendered, React gives it a state of 0, each time we call the function useState() has the current state assigned to counter?
(2)
increment
binds the value of counter
when it's created, and that's 0. It's a function which sets the counter to that original value + 1, that is, increment
is setCounter(1)
and you're calling it twice. Then when the component is re-rendered it'll be rebound to being effectively setCounter(2)
some of this stuff ends up being pretty non-obvious in React unfortunately
The usual way to deal with this is something like:
which will make it behave like you expect it toone question though
we say
counter
is a const
but when the function increment occurs, how can it modify counter
?
Everything between start and end is code that runs every
render
.
setCounter
triggers a re-render.
This means that the const is not modified because it is a different const.
Equivalent example:
Also this is more accurate:
Also if you are wondering how the values can be different. It is because useState saves its state outside of the rendering cycle.one thing I don't understand though
When we pass in an arrow function as argument in the
setCounter()
function, how is that different from passing counter itself, I mean, what's special about the arrow function in this case?Its called a callback.
its when you send a
function
as an argument/parameter.
example:
UseState is a function that returns an array. So just like you can use
const
for an array; const
only prevents reassignment of the variable identifier itself. The array reference remains constant, but the elements inside the array can be mutated (like with arr.push()
)This is basically what is happening behind the scenes simplified to javascript:
yep I see, thanks !