0

I'm working on learning React and I'm following this tutorial https://reactjs.org/docs/state-and-lifecycle.html and in it an interval is set inside a react component class and the syntax used is setInterval(() => this.tick(), 1000) where tick is a method in the Clock component. My question is this: So this arrow function simply calls this.tick() when its called, and setInterval will call it, so what is the difference between just passing in this.tick without wrapping it in an arrow function like so setInterval(this.tick, 1000)? I thought there would be no difference, but removing the wrap in an arrow function and the clock doesn't work. Whats going on? Here is a link to a codepen demonstrating the issue https://codepen.io/anon/pen/aKNJGd?editors=0011 (line 12)

Hastradamus
  • 101
  • 8

1 Answers1

1

Sounds related to how this works in Javascript. With the arrow function, you get this from the React component via closure scope. Without the arrow function, the this.tick that gets called has a different (or no) this.

Add this in your constructor and it will work without the arrow function.

this.tick = this.tick.bind(this)

Samantha Branham
  • 7,112
  • 2
  • 30
  • 44