Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compare two ways of getting previous state from a React component, when setting its new state.
class Player extends React.Component {
constructor() {
super()
this.state = { score: 0 }
}
increaseScore() {
// 1. Get previous state from this.state
this.setState({ score: this.state.score + 1 })
// 2. Get previous state from the callback function
this.setState((prevState) => {
return { score: prevState.score + 1 }
})
}
}
@frayhan32
Copy link

frayhan32 commented Mar 10, 2018

Awesome thank you

@piotros
Copy link

piotros commented Aug 17, 2018

Second example can look like this:

this.setState(prevState => ({
    score: prevState.score + 1
})

@nikhilknoldus
Copy link

nikhilknoldus commented Dec 28, 2018

👍

@pawan-prusty
Copy link

pawan-prusty commented May 21, 2022

How to do this with functional component

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment