I have an example here with a simple state called counter. In the componentDidMount, I am getting 0 instead of 3 during console.log and during unmount, I am getting the counter number from button click instead of 0. I am confused as to how does it really works? Here is the code:
import React, { Component } from 'react'
class TestNumber extends Component {
constructor(props) {
super(props)
this.state = {counter: 0}
}
componentDidMount() {
console.log('Mount Called')
this.setState({counter:3})
console.log(this.state.counter)
}
componentWillUnmount() {
this.setState({counter:0})
console.log('Unmount Called')
console.log(this.state.counter)
}
handleClick = () => {
this.setState({counter: this.state.counter + 1})
}
render() {
return (
<div>
<h2>{this.state.counter}</h2>
<button onClick={this.handleClick}>
Click me
</button>
</div>
)
}
}
export default TestNumber