Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat vs push adding new array in react best practice

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?

like image 367
Zea Lith Avatar asked Jan 12 '17 15:01

Zea Lith


People also ask

Is concat or push faster?

concat performs at 0.40 ops/sec, while . push performs at 378 ops/sec. push is 945x faster than concat ! This difference might not be linear, but it is already is already significant at this small scale.

What is the difference between push and concat?

The push() adds elements to the end of an array and returns the new length of the array. Thus your return here is invalid. The concat() method is used to merge arrays. Concat does not change the existing arrays, but instead returns a new array.

What can I use instead of push in React?

You should use concat() function in place of push() because react does not work good with object mutability react people emphasize react developers to keep the state of immutable.

What is the best method to update state in component React?

setState() . This is a function available to all React components that use state, and allows us to let React know that the component state has changed. This way the component knows it should re-render, because its state has changed and its UI will most likely also change.


1 Answers

Immutability is used in react and not only because of redux. React component's state should not be mutated directly. According to the docs:

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

In addition, immutability also helps in reconciliation. If props are immutable, you can make a shallow equality check to see if it's changed or not, and render accordingly.

In your code updatedList is cloned to a new array using Object#assign. Now you can Array#push to the array, without changing the original one. Using Array#concat is a bit shorter, and more readable:

const updatedList = this.state.list.concat(response.result);
like image 102
Ori Drori Avatar answered Sep 17 '22 20:09

Ori Drori