I have a React component that starts with a count down timer where the component gets unmounted either when a button is pressed or the countdown reaches zero. It's implemente like this:
state = {
counter: 60,
};
componentWillMount() {
this.doCountDown();
}
doCountDown() {
if (this.state.counter < 1) {
return this.props.tryAgain();
}
this.setState(prevState => ({ counter: prevState.counter - 1 }));
setTimeout(() => this.doCountDown(), 1000);
}
This isn't a duplicate of Unmounting a Component with a SetInterval in React.
In my case here I have a recursive event going on so I can't clear the interval like the example in the link mentioned.
Anyone have any ideas on what to do?
For more explanation: this.props.tryAgain()
will change the state higher up which causes this component to unmount. When this occurs, due to the timeout, the state still attempts to change while the component has already unmounted. This indicates a memory leak and is bad practice. So I'm trying to find out a good work around to prevent that from happening.
You need to call the call the clearInterval
method on unmount:
componentWillUnmount() {
clearInterval(this.timeout)
}
doCountDown() {
if (this.state.counter < 1) {
return this.props.tryAgain();
}
this.setState(prevState => ({ counter: prevState.counter - 1 }));
this.timeout = setTimeout(() => this.doCountDown(), 1000);
}