Hlaing_Min_Than's avatar

React UseState Hook

is anyone can explain what is the benefit of using function update vs direct update to state ? .i think it's alittle bit complex for me.can i get any example for better understanding ?

setCount(++count);
setCount(prevCount=>++prevCount);//what is the benefit of using this
0 likes
4 replies
Sinnbeck's avatar

In the first example you get the value of the count as it is at that point in execution (when you hit the line).

The second calls the function at the end of execution, in case the state has somehow changed

I rarely need the second method (it was more needed in the old class based days)

1 like
Sinnbeck's avatar

Also be sure you don't mutate variables directly

setCount(count + 1)
1 like
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@Hlaing_Min_Than well imagine you update the count 2 times in the same "flow". Then it would in the first example be set the the same value twice

Please or to participate in this conversation.