JavaScript React Components 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!

Shane Finlayson
Shane Finlayson
13,172 Points

Here give this a try

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.