log101
log101

Reputation: 17

-js- React "component did mount" example

I'm trying to get started with react. Having examining the code examples I came across with a pretty strange thing. This is the link [React tutorial]. This is the code from the lifecycles section;

componentDidMount() {
this.timerID = setInterval(
  () => this.tick(),
  1000
);
}

So, when setting the interval why an arrow function is used ? I tried otherwise(this.tick() itself) but it didn't work as expected.

Upvotes: 0

Views: 800

Answers (1)

Frazer Kirkman
Frazer Kirkman

Reputation: 1154

setInterval needs to be passed a function reference, so you could write

setInterval(  () => this.tick(),  1000  );

This doesn't run this.tick, it simply tells setInterval to run tick when it chooses to. The arrow function binds 'this' to be your component.

However setInterval( function () { this.tick(); }, 1000 ); does NOT bind this to be your component, so you would need to write setInterval(this.tick.bind(this), 1000 );

If you write setInterval( this.tick(), 1000 ); then tick is run before it is passed to setInterval, and the return value of tick is what will be used by setInterval.

I hope that makes it clear. setInterval just wants a reference to the function :)

Upvotes: 1

Related Questions