Skip to content

Instantly share code, notes, and snippets.

@ambethia
Created August 22, 2017 19:34
Show Gist options
  • Save ambethia/1e79c46d5065ff27d162235717c50f05 to your computer and use it in GitHub Desktop.
Save ambethia/1e79c46d5065ff27d162235717c50f05 to your computer and use it in GitHub Desktop.
const item = 'FOOBerries!'
// Anti-pattern, don't do this!
this.state.list.push(item)
this.setState({ list: this.state.list })
// Correct way to do what the anti-pattern did:
const nextState = this.state.list.slice()
nextState.push(item)
this.setState({ list: nextState })
// ...but we can do better.
// Better!
this.setState({
list: [item, ...this.state.list]
})
// But sometimes we need to mutate more than just a simple array...
// Using immutability helper (https://github.com/kolodny/immutability-helper)
this.setState(
update(this.state, {
list: { $push: [item] }
})
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment