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 setState
function?
TL;DR
To allow the
setState
function to use the actualprevious value
of the state.
Longer version
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
.jsx1234567891011121314
If you predicted that the new state would not be abc
, then kudos to you.
If not, then let's discuss what happened.
.jsx1234567891011
We indeed called setState
3 times, but that does not mean the value of the state
variable will update after calling setState
.
Solution: pass a function to setState
.jsx123456789
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.
.jsx1234567891011121314
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.
.jsx1234567891011
Conclusion
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.