Many folks promote immutability because they use redux altogether with react, but I'm still seeing people using push instead of concat.
Take this code for example:
submitComment() {
console.log('submitComment: '+JSON.stringify(this.state.comment))
APIManager.post('/api/comment', this.state.comment, (err, response) => {
if (err){
alert(err)
return
}
console.log(JSON.stringify(response))
let updateList = Object.assign([], this.state.list)
updatedList.push(response.result)
this.setState({
list: updatedList
})
})
}
in this case does it matter at all? What's the issue with push above?
Immutability is used in react and not just by redux. The state of the React component should not be mutated directly. According to the documents :
Never modify this.state directly, as calling setState() afterwards may override the mutation you made. Treat this state as if it were immutable.
Furthermore, immutability also helps in reconciliation. If the props are immutable, you can perform a shallow equality check to see if it has changed or not, and render accordingly.
In your code, updatedList is cloned into a new array using Object#assign . Now you can Array#push to the array, without changing the original. Using Array#concat is a bit shorter and more readable:
const updatedList = this.state.list.concat(response.result);