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

Stanislaus Slupecki
Stanislaus Slupecki
1,986 Points

Scope in React

So, I've been going through the React.js lessons. And I have been having a bit of trouble following scope in React. I understand that there are times when you don't need to use .bind() to make sure what this points to in a parent object is right, while other times it is implied. Take, for example, 'this' in these code pieces from the Stopwatch component from the later lessons:

componentDidMount : function() { this.interval = setInterval(this.onTick, 100); },

componentWillUnmount : function() { clearInterval(this.interval); }

In these examples, shouldn't "this" point to the parent componentDidMount/componentWillUnmount functions themselves? Is this React preserving "this"? Or is this some of the rules governing scope with timers/intervals in JavaScript that overrides normal behavior for "this"? Or am I mistaken about normal behavior of "this" in JavaScript?

2 Answers

Michael Liendo
Michael Liendo
15,326 Points

You got it. Since componentDidMount is a lifecycle method, react calls it and automatically binds this to the component. The important part is that it's only the case because it's a react lifecycle method. If you tried it with a method you created, you would have to explicitly bind this.

Michael Liendo
Michael Liendo
15,326 Points

Great question! So setTimeout returns the created timer. So when the component mounts we're saying, "hey, assign that timer as a property on the component." by saying this.interval. In that context, this refers to the component, and interval refers to the returned timer.

That way, when the method gets called to destroy the timer, we can say reference the timer in componentWillUnmount by calling this.interval, specifically to destroy the timer using clearInterval

Stanislaus Slupecki
Stanislaus Slupecki
1,986 Points

Alright, that answers part of my question. But why does 'this' refer to the component in this context? Shouldn't 'this' refer to the function? Or is this because creating a function using this syntax does not override 'this', making it still refer to the component? Or is this some feature of React that preserves 'this' in certain contexts?