React docs implements a clock for demonstrating concepts such as states and lifecycle.
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
I was curious about why componentDidMount
's setInterval uses an arrow function. It does't work without it, either by:
Implementation ONE:
setInterval(this.tick(), 1000)
Which passes the return of tick
instead of calling it, either by doing:
Implementation TWO:
setInterval(this.tick, 1000)
Which throws an setState is not a function
error.
It was asked before on stackoverflow, but the accepted answer is wrong, since it suggests coding IMPLEMENTATION TWO.
I guess the error is caused due to the scope of this
. Inside setInterval, there's no this.setState
, that's why binding solves it (as one of the others answers point out).
However, I would like to know how an arrow function can solve what otherwise would require binding.