My Doubt is related to using timer in react component, as per my understanding once component unmount its all properties/methods will not exist after that.
As per DOC:
componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any DOM elements that were created in componentDidMount.
Check this snippet:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {count: 1};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
3000
);
}
componentWillUnmount() {
//clearInterval(this.timerID);
}
tick() {
console.log('called', this.props.no);
}
render() {
return (
<div>
<h1>Clock {this.props.no}</h1>
</div>
);
}
}
class App extends React.Component {
constructor(){
super();
this.state = {unMount: false}
}
click(){
console.log('unmounted successfully');
this.setState({unMount: !this.state.unMount})
}
render(){
return (
<div>
<button onClick={() => this.click()}>Unmount first</button>
{!this.state.unMount && <Clock no={1}/>}
<Clock no={2}/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'/>
Here i am rendering two clock component and unmounting the first one onclick of button that is happening successfully and it's updating the DOM also, even after unmounting the first component timer is printing the props values properly by console.log().
I am not clearing the Timer in componentWillUmount:
componentWillUnmount() {
//clearInterval(this.timerID);
}
My Doubt is:
this.timerID = setInterval(
() => this.tick(),
3000
);
tick() {
console.log('called', this.props.no);
}
I am passing a class method as callback in timer so once component has been unmounted how tick function exist, How this timer is resolving this keyword and the tick function after the component unmounted? How this.props.no is having the correct value? why it's not throwing the error:
can't read tick of undefined or tick is not defined
How it is maintaining the references to these functions?
Help me what i am missing here, please provide any reference or example.