React setState callback function
What is the callback function in a setState for?
October 25th, 2021
October 25th, 2021
callback function
to the setState
function?TL;DR
To allow the
setState
function to use the actualprevious value
of the state.
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 setState
.
setState
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.
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.