2

will below code work? Saw it somewhere not sure why the author did that

this.setState({
  messages: this.state.messages.concat({
    text: 'new message'
  })
})

Normally I'll do

this.setState({
  messages: [
    ...this.state.messages,
    {text: 'new messages'}
  ]
})

which one is appropriate?

1 Answer 1

1

Either works. concat is more widely supported but if you're using react you're likely transpiling anyway, right? So whichever is more readable to you. I prefer the spread syntax since it's shorter.

Both just make shallow copies. That is, the array object is a new reference, but any objects in the array are the same reference (and value types are copied, as usual).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.