Using setInterval in React Component

Viewed 11288

I was reading the tutorial on the official react website. In the example about life cycle methods, under the componentDidMount method, a timerID is set to the setInterval function.

My question is even though the timerID was initialized, it was never called throughout the application, how does the application work without explicitly calling timerID anywhere in the application. Here is the code below.

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')

);
3 Answers

In this react document it's written that

We will tear down the timer in the componentWillUnmount() lifecycle method

So, this.timerID will be used in componentWillUnmount() lifecycle method to stop timer.

Related