Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React Basics (2018) Understanding State Update State Based on Previous State

Is my understanding of state handling correct?

I find the explanation in the video lacking in clarity exactly what's the problem that makes the setState callback function version of setState the preferred solution. I also found the React docs linked in teachers notes very poor from a pedagogical perspective.

In general, I want to thoroughly understand a problem before learning a solution to it...

This is my understanding of how it works - if you guru's spot something wrong, please share.

Imagine two different scenarios when passing a state change Object to setState:

a. If you want to set a state to a fix value. For example state.text: "hello". If the setState method detects that there's also another setState call that wants to set the same components state to state.text: "world", then the last one, "world" will have precedence, hence state.text will be set to "world". It makes sense, since it cannot merge two conflicting state changes, and it's not good from a performance perspective to set it to "hello" first and then immediately changing it to "world".

b. If you want to set a state to a value dependent on the current state, like in the video example increase or decrease current value, then you don't want to perform only the last setState call when there are multiple calls that wants to change the same components state. You want all of them to be performed in the order they came in to setState. The problem with using the object parameter version of setState is that it will take a snapshot of the state, pass the object as a parameter to setState with the state.score already calculated to a value, and it will be handled by setState as in scenario a - it will pick the last of all concurrent state change requests.

So the solution to the problem scenario in b, is to inform setState that it must run the provided state change callback method when itΒ΄s time to set the state: the increaseScore method - then setState knows that it must run all concurrent setState calls that's currently in queue to set the state for the component.

FYI I read through this trying to get a better understanding: https://www.freecodecamp.org/news/functional-setstate-is-the-future-of-react-374f30401b6b/