Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: what happens to a function when component stop being rendered

I have a function defined in a component, it start and keeps running when the component is mounted. What happens to the function when the component stops being rendered or dismount?

class MyComponent extends React.Component<> {
  _count = () => {
    console.log('a second passed');
    setTimeout(1000, this._count);
  }

  componentDidMount() {
    _count();
  }
}
like image 622
Hua Avatar asked Mar 17 '26 18:03

Hua


1 Answers

The timer will keep running unless it gets cleared, so you will want to clear it in componentWillUnmount which is used to "perform any necessary cleanup...such as invalidating timers":

class MyComponent extends React.Component {
  _count = () => {
    console.log('a second passed');
    this.countTimer = setTimeout(this._count, 1000);
  }

  componentDidMount() {
    _count();
  }

  componentWillUnmount() {
    clearTimeout(this.countTimer);
  }
}
like image 186
Brian Adams Avatar answered Mar 20 '26 07:03

Brian Adams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!