React setState callback function
What is the callback function in a setState for?
Monday, October 25, 2021
Why do we need to pass a
callback function to the
To allow the
setStatefunction to use the actual
previous valueof the state.
What if we call the
setState function simultaneously?
From the example below, at first glance, we might say the state will be
abc after clicking the button.
Try to play with the code below
If you predicted that the new state would not be
abc, then kudos to you.
If not, then let's discuss what happened.
We indeed called
setState 3 times, but that does not mean the value of the
state variable will update after calling
Solution: pass a function to
Passing a function to
setState will allow us to get the previous state value from the function's first argument.
Now check the result of our updated code.
How did it work?
Each callback function would have a reference to the recent state change(if there is any) as shown in the commented code below.
Pass a callback function to
setState if it might be called multiple times
and the new state needs to be calculated based on the previous state.