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

jaredabbadusky
jaredabbadusky
6,374 Points

Why not just add a totalScore property to the state object?

Before I watched Guil's solution, I solved this by adding a totalScore property to the state object so that I could simply update this alongside the individual player's score when handleScoreChange is called. That way it tallies up the total score whenever any of the players scores are updated.

I kept the totalPlayers prop passing to the Header and added a totalScore prop (this.state.totalScore) down to the Header. This seems to keep the Stats Component clean without any logic of it's own. and requires no calculations using the reduce method.

I can see how you can show off the reduce method as a way to calculate the score, but wouldn't it be cleaner just to add a totalScore property to state?

Strange Learning
Strange Learning
Treehouse Guest Teacher

I would imagine Guil is aware of this solution, but felt this was a good opportunity to show the reduce pattern, as it is very often seen when dealing with React / React Native.

FWIW, I did the same solution you did.

1 Answer

I did it somewhat like Guil's solution, but adding the logic in the App component, and only passing the already computed values as props. But I think his solution is better, because it helps maintain the granularity of the app, and the individual responsibilities of the components. If the Stats component displays the stats, then it'd be the one to make the appropiate stats calculations and show the value. That way, if later you need to modify the stats logic for any reason, you can (logically) find it quickly in the Stats component, which makes sense, and not searching for it in an event handler or wherever else.