React’s setState method with prevState argument

Both signatures can be used, the only difference is that if you need to change your state based on the previous state you should use this.setState(function) which will provide you a snapshot(prevState) from the previous state. But if the change does not rely on any other previous value, then a shorter version is recommended this.setState({prop: newValue})

this.setState(prevState =>{
   return{
        ...prevState,
        counter : prevState.counter + 1
   }
})

this.setState({counter : 2})

Leave a Comment