0

Unable to stop setInterval in react using componentWillUnmount() when the timer hits at 7 class component

export default class App extends React.Component{
  constructor(props){
    super(props);
    this.state={
      counter:0
    }
  }

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

  componentWillUnmount(){
    if(this.state.counter===7){
      clearInterval(this.timerID);
    }
  }

  timer = () => {
    this.setState({
      counter: this.state.counter+1
    })
  }
Syed
  • 1
  • React components are not meant to unmount themselves, you would need a wrapper component that state/props would use to render / or not.. – Keith Oct 24 '22 at 11:59

1 Answers1

1

I think here is little misunderstanding, componentWillUnmount run its content when component unmount, and not unmount component when some conditions met.

To make this code work as expected, you need to unmount your component when this.state.counter will be equal to 7.

If you want to stop your counter to work when this.state.counter will be equal to 7, then try to look into componentDidUpdate it fire every time after component update, so it will work