Skip to content

Instantly share code, notes, and snippets.

@klikstermkd
Last active February 8, 2023 12:11
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save klikstermkd/e56e120ad9559aa44dfeaa3b13cfb25d to your computer and use it in GitHub Desktop.
Save klikstermkd/e56e120ad9559aa44dfeaa3b13cfb25d to your computer and use it in GitHub Desktop.
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

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

👍

@pawan-prusty
Copy link

How to do this with functional component

@shoaib9121
Copy link

@pawan-prusty With functional component you could do something like below:

const [score, setScore] = React.useState(0);

and somewhere later in the code

setScore(prevState => {
   return prevState + 1;
})

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