JavaScript React Basics Understanding State Update State Based on Previous State

I'm confused why you'd use the callback when updating state? Seems like an extra step when it gave you the same results

I'm confused why you'd use the callback when updating state? Seems like an extra step when it gave you the same results without adding the extra callback.

3 Answers

Dylan Thunn
Dylan Thunn
22,657 Points

You don't technically have to it, it is just a more stable way of doing it for react, with a small app though it is probably overkill. Once you get to using hooks to update state it won't really matter.

Dan Sutherland
Dan Sutherland
1,459 Points

prevState is the value of the state BEFORE the callback is fired, whereas this.state.stateName holds the value of state to be altered at the time that callback is being fired. Most of the time this won't be an issue but as React can batch render updates, sometimes if a state is being updated by a variety of methods you can get get unexpected results if your updates are iterative.

thank you :)