Last active
February 8, 2023 12:11
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } | |
}) | |
} | |
} |
Second example can look like this:
this.setState(prevState => ({
score: prevState.score + 1
})
👍
How to do this with functional component
@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
Awesome thank you