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 Basics๏ผš Making the Stopwatch Tick.

Hi,

my question is related to https://teamtreehouse.com/library/making-the-stopwatch-tick.

There are lines of code:

onTick: function() {
  if (this.state.running) {
    var now = Date.now();
    this.setState({
      previousTime : now;
      elapsedTime : this.state.elapsedTime + (now - this.state.previousTime),
  });
};

Each time the component is rendered by setState, we assign the previous time to now, how come the next line of code where we calculate elapsedTime is not affected? Why we don't get the result of this.state.now + (now-now)? Do you know what I mean? These operations are simultaneous, right?

1 Answer

Elise Kain
Elise Kain
54,392 Points

this.setState does not modify the current state (this.state) immediately. It's basically placed in queue (at least that's how I imagine it) where React processes the changes of state for the component in the order they are received. See the React setState Documentation where they say:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

This is why you can reference the existing value for this.state.previousTime when creating the value for elapsedTime in the example, and always be certain it will be the current this.state.previousTime.

Instead of reading the items in between the curly brackets as instructions for React to process in order, you are creating a static object that React will then take and use to set the updated state.

[mod edit: comment -> answer]