Skip to content

Instantly share code, notes, and snippets.

@aslan144
Last active January 25, 2018 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aslan144/d0be01f148dcf252a68d979628fea119 to your computer and use it in GitHub Desktop.
Save aslan144/d0be01f148dcf252a68d979628fea119 to your computer and use it in GitHub Desktop.
[State] setState #reactn
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