1

I'm learning React, following their tutorial. They made a clock component which updates itself, and has these functions:

tick () {
    this.setState({
        date: new Date()
    });
}

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

They called setInterval with an anonymous (arrow) function, that only calls tick.

My Question:
Why does the above work, while placing this.tick like I did below doesn't?

componentDidMount() {
    this.timer = setInterval(
        this.tick,
        1000
    );
}
  • 1
    Because with the code at the end of your question, `this` won't refer to the component when `tick` is called. `setInterval(this.tick.bind(this), 1000)` would work, though. See the linked question's answers for details. – T.J. Crowder Mar 04 '17 at 16:27
  • 1
    Or you can bind the context of `tick` to the component, e.g in your constructor: `this.tick = this.tick.bind(this);` then you can use `this.tick` like the later case. – sonlexqt Mar 04 '17 at 16:30
  • setInterval maps a different 'this' if the passed function is not an arrow function. That's one of the new features introduced with arrow functions. – Bulent Vural Mar 04 '17 at 16:30

0 Answers0