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) Designing Data Flow Adding Players to the Scoreboard

Can someone explain for me why do we use this.setState(this.state)?

I don't understand why do we use "this" and why do we use this.setState(this.state)?

3 Answers

Giovanni P.
Giovanni P.
4,803 Points

While the OP has probably already figured this out, it might be good for there to be an actual answer in case others are looking for it.

The reason we call this.setState( this.state ) is so that React actually rerenders the page with the new state. If we just set this.state and didn't call this.setState( this.state ), the state variable would change, but React wouldn't know it is supposed to rerender the page.

I hope that helps!

I Dilate
I Dilate
3,983 Points

Hi shyarkhalil,

Do you have any experience with JavaScript yet?

There's a great lesson that will shed some light on how "this" works in JavaScript, inside the Beginning Javascript track. If you haven't covered that yet, then I urge you take it before moving onto attempting anything with React.

I Dilate
I Dilate
3,983 Points

Here's a good summary of how "this" works, from the Full Stack Javascript track...

Understanding "this" in JavaScript

Hi I Dilate! But you didn't answered me why do we use this.setState(this.state)?