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 (retired) Stateful Components Updating State

Qian Chen
Qian Chen
33,579 Points

incrementScore and decrementScore should use the function version of setState

I think the incrementScore and decrementScore should use the function version of setState, which looks like this:

incrementScore: function(){
  this.setState(function(prevState) {
    return {
      score: prevState.score+1
    };
  });
}

Because you cannot guarantee to get most up to date state across multiple calls of incrementScore, which is described here: https://facebook.github.io/react/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

1 Answer

akak
akak
29,445 Points

You are correct, that is now the preffered way of updating the state. The React docs were rewritten in October 2016 to put more focus on the function in setState. A the time the course was recorded the old docs didn't really indicate there is a lot more into the function then they do now. Old docs: https://web.archive.org/web/20160517152245/http://facebook.github.io/react/docs/component-api.html

I have written 3 apps in React without using the function and they work just fine. So yeah, it's better to follow new guidelines but writing app like shown in the videos will probably rarely (if ever) cause a problem.