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 Basics (retired) Designing Data Flow Building the Statistics Component

Jesse Thompson
Jesse Thompson
10,684 Points

Why does the total points automatically update?

Im not too sure I might have figured it out. But is it because the onScoreChange function, line "this.setState(this.state);"??

It seems as if REACT is doing a lot more than specified here, I guess this is the magic of state and component classes?

Like why is the totalPoints function running everytime the state is changed?

Its not being told to run everytime the state changes. This is a great feature but my question is how?

const totalPoints = props.players.reduce(function(total, player){
        return total + player.score;
    }, 0);

1 Answer

Mike Jensen
Mike Jensen
11,718 Points

Basically you are right, this is an example of where React automates the underlying "plumbing" of an app in a powerful way, which simplifies what would otherwise be a lot of cross-checking and manual updating busywork for us.

Essentially, what happens is as follows:

  1. A user interacts with the app and requests a player's score to be changed
  2. Our code runs this.setState() which is a request for React to update its model of the application data (state)
  3. When application state is modified through this correct, official channel, it prompts React to check our application for any places where the state change requires re-rendering, and therefore run the relevant render functions again
  4. After running these functions again, React compares the original and resulting new VirtualDOM (model of our application structure/content), obtaining an efficient path of changes required to then turn into direct DOM manipulations (instructions to the web browser to update the page content)