Created
September 22, 2019 12:06
-
-
Save dandelionadia/03ca36e78cf2bcea1dd116030cc523ac to your computer and use it in GitHub Desktop.
React setState/useState comparison
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 MyComponent extends React.Components { | |
constructor () { | |
this.state = { | |
a: 0, | |
b: 'foo' | |
} | |
} | |
handerClick = () => { | |
this.setState({ | |
a: 1 // 1 | |
}) | |
// this.setState({ | |
// a: this.state.a + 1 // 1! | |
// }) | |
this.setState((prevState) => { | |
return { | |
a: prevState.a + 1 // 2 | |
} | |
}) | |
} | |
render() { | |
return null | |
} | |
} |
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
function MyComponent () { | |
const [a, setA] = useState(0) | |
const handerClick = () => { | |
setA(1) | |
// setA(a + 1) // 1! | |
setA((prevA) => { | |
return prevA + 1 // 2 | |
}) | |
} | |
return null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment