DEV Community

Cover image for Updating state in react based on the previous state
Shaban-Eissa
Shaban-Eissa

Posted on

Updating state in react based on the previous state

Suppose the age is 42, let's see the difference between first and second function

Image description

in first function, after one click, the age will only be 43 rather than 45! This is because calling the set function does not update the age state variable in the already running code. So each setAge(age + 1) call becomes setAge(43).

in second function, you may pass an updater function to setAge and Here, age => age + 1 is your updater function. It takes the pending state and calculates the next state from it.
React puts your updater functions in a queue. Then, during the next render, it will call them in the same order:
age => age + 1 will receive 42 as the pending state and return 43 as the next state.
age => age + 1 will receive 43 as the pending state and return 44 as the next state.
age => age + 1 will receive 44 as the pending state and return 45 as the next state. There are no other queued updates, so React will store 45 as the current state in the end.

Image description

Top comments (0)