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?


To allow the setState function to use the actual previous 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

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.

Solution: pass a function to 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.

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.