react prevstate code example
Example 1: react prevstate
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
Example 2: componentDidUpdate
componentDidUpdate(prevProps, prevState) {
if (prevState.pokemons !== this.state.pokemons) {
console.log('pokemons state has changed.')
}
}
Example 3: prev props
componentDidUpdate(prevProps) {
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
Example 4: this.setstate prevstate
this.setState(prevState => ({ n: !prevState.n }))
Example 5: prevstate in react
handleClick() {
this.setState(prevState => {
return {
count: prevState.count + 1
}
})
}