I’ve completed the recommended scrimba course on react and my below code is working fine.
However, I see in the solution that prevState isn’t used to setState.
When should prevState be used and under what conditions is it okay to just use this.state?
Your code so far
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
// change code below this line
this.increment = this.increment.bind(this)
this.decrement = this.decrement.bind(this)
this.reset = this.reset.bind(this)
// change code above this line
}
// change code below this line
reset(){
this.setState({count: 0})
}
increment(){
this.setState(prevState => {
return {
count: prevState.count + 1
}
})
}
decrement(){
this.setState(prevState => {
return {
count: prevState.count - 1
}
})
}
// change code above this line
render() {
return (
<div>
<button className='inc' onClick={this.increment}>Increment!</button>
<button className='dec' onClick={this.decrement}>Decrement!</button>
<button className='reset' onClick={this.reset}>Reset</button>
<h1>Current Count: {this.state.count}</h1>
</div>
);
}
};
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
.
Link to the challenge: