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!

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

Jeremy Ashcraft
Jeremy Ashcraft
14,786 Points

How do the totalPoints keep updated using Guil's solution?

Guil's Solution: const totalPoints = props.players.reduce( (total, player) => { return total + player.score; }, 0);

With Guil's solution, shouldn't totalPoints be assigned a value only once (at the time the stats component is rendered into the DOM)?

Yet the total points score updates every time the score changes.

1 Answer

Jason Pallone
Jason Pallone
11,340 Points

The Reduce method takes 2 arguments, accumulator and the item it is currently looping through in the array, so by returning total + player.score we are using dot notation on each player object in the array to get their individual scores. Each time reduce loops through, it adds the player score for the current array index to total. Then at the end once it has looped through the whole array, you have the total points for each player combined returned to your totalPoints variable. Now whenever you update a player score, that is changing the state, which makes the component re render and update the state, reflecting a new total for totalPoints. If you need me to clarify more please just ask! Hope this helps!

Dan Jordan
Dan Jordan
7,883 Points

Jason Pallone - does this mean that any component using state is automatically re-rendered when the state is updated, or only components within the render() method are updated, as we see in App.js?