Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript React Basics 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/