-
-
Save aslan144/d0be01f148dcf252a68d979628fea119 to your computer and use it in GitHub Desktop.
[State] setState #reactn
This file contains hidden or 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
First, whenever you're updating the state based off the previous state (like count in your example), you'll want to use functional setState. | |
this.setState((currentState) => ({ | |
count: currentState.count + 1 | |
})) | |
If you don't, you'll most likely run into some issues. https://medium.com/@shopsifter/using-a-function-in-setstate-instead-of-an-object-1f5cfd6e55d1 | |
Second, I don't love that pattern. Can't you just calculate if it's even before you setState? | |
this.setState((currentState) => { | |
const newCount = currentState.count + 1; | |
const countType = newCount % 2 === 0 ? 'even' : 'odd' | |
return { | |
count: newCount, | |
countType, | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment