Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

75
Visualizações
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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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);
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda