Let's take a look at this class.
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timer = setInterval(() => (this.tick()), 1000);
}
tick() {
this.setState({date: new Date()});
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return(
<div>
<h1>Clock</h1>
<h1>It is {this.state.date.toLocaleTimeString()}.</h1>
</div>
);
}
}
ReactDOM.render(<Clock />, document.getElementById('root'));
As you can see, this is a <Clock />
class.
First Question:
this.timer = setInterval(() => (this.tick()), 1000);
Why does this work instead of, say:
this.timer = setInterval(this.tick(), 1000);
The first one sets a function as a callback to the first argument of setInterval
and actually calls the function in the callback.
The second invokes the function on load.
Second Question:
Let's say I want to put the code as:
this.timer = setInterval(this.tick, 1000);
Can you? Yes, you can.
You would have to bind the function in the constructor.
constructor(props) {
super(props);
this.state = {date: new Date()};
this.tick = this.tick.bind(this)
}
Why? Well, you actually have to call the function and that is what binding does behind the scenes.
However, if you don't want to explicitly bind
the function, you can declare it using the ES6 arrow syntax.
tick = () => {
this.setState({date: new Date()});
}
This achieves the same effect of binding.
Thus, you can still do this, without having to explicitly bind
the function.
this.timer = setInterval(this.tick, 1000);
If you want to know more about binding, I will refer you to this very comprehensive guide on binding. It got technical pretty fast for me, so take your time.
If you're wondering how I found it, I was looking through the React website and found the link.
I hope it helps you!
Top comments (0)