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 Components (2018) Managing State and Data Flow Building the Statistics Component

Friedrich Coen
Friedrich Coen
2,648 Points

Callback function

Hi, I am having difficulties making sense out of this piece of code even though I understand what it does.

handleScoreChange = (delta,index) => { this.setState( prevState => ({ score: prevState.players[index].score+= delta }));

I am struggling with the prevState part. Before adding that function the code read score: this.players[index].score +=score which made sense to me.. But in order to get the update in the state always in time it got transformed into the call back function with prevState as argument. Can anyone explain me what the prevState represents and why you can nest it in the following way? ( score: prevState.players[index].score+= delta)

Thanks a lot!

1 Answer

Here give this a try https://reactjs.org/docs/state-and-lifecycle.html

if that doesn't help let me try to explain. If we don't use the prevState part and instead just leave it the way it was score: this.player[index].score += delta their is a chance that it will not update immediately and instead batch it together with other setState() calls to increase performance. If we use a function with the .setState() call like so setState( (prev) => {do something} the first parameter we pass it will hold the value of the previous state. We can then alter the previous state with the changes we desire.

I really hope this helps a little, hopefully someone smarter will be along shortly to explain it in more detail.