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

240
Visualizações
How to prevent my array to updated again and again on onChange Function in React JS?

I have cloned an array and I have an onChange function. On calling onChange function my original and cloned array is updating according to the updated onChange value. But I don't want to update my cloned array. How can I do this ?

My code -

const clonedArray = [...originalArray];

const onChange = (id:number, value: string): void => {
    const arrayData = originalArray;
    
    const selectedData = arrayData.find(
        (data) => data.myId === id
    );
    if (selectedData) {
        // updating my originalArray according to new changed value;
    }
}

this onChange function is also updating my clonedArray. I don't wanna update my clonedArray. How can I do this ? What is the solution useMemo or something ? Can anyone tell me the solution for it ?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Issue

This issue is state object/array mutation. You are mutating elements in an array and seeing the mutations manifest in a "copy".

Firstly, const clonedArray = [...originalArray]; is only a shallow copy of the originalArray, not a clone. This means that other than the array reference itself, all the elements in clonedArray still refer to the same elements in originalArray.

Secondly, if later you are making changes in originalArray and you are seeing them manifest in clonedArray then you are definitely mutating the element references instead of creating new references.

Solution

You are looking for the Immutable Update Pattern. When updating state in React it is necessary to shallow copy not only the root object/array that is being updated, but all nested state as well. To help with endeavor, especially when updating arrays, you will want to also use functional state updates so you can correctly update from the previous state.

For this I'm assuming (based on a comment that originalArray was in state) that your state looks something like this:

const [originalArray, setOriginalArray] = useState([]);

The change handler/state update (just an example since I don't know your exact update requirements)

const onChange = (id: number, value: string): void => {
  const selectedData = originalArray.find((data) => data.myId === id);

  if (selectedData) {
    // updating my originalArray according to new changed value
    // Array.prototype.map shallow copies the array into a new array reference
    setOriginalArray(originalArray => originalArray.map(data => data.myId === id
      ? {               // <-- updating element into new object reference
        ...data,        // <-- shallow copy previous data element
        property: value // <-- update property with new value
      }
      : data            // <-- not updating, pass previous object through
    );
  }
}

Once you are correctly updating the array elements, then no mutations will occur to anything that may also be referencing the state.

about 4 years ago · Juan Pablo Isaza Relatório

0

you can use useMemo with empty dependency array. whenever originalArray updates, clonedArray doesn't change.

import { useMemo, useState } from "react";
const arr = [1,2,3]
export default function App() {
  const [originalArray, setOriginalArray] =  useState(arr)
  const clonedArray = useMemo(() => originalArray, [])
      
  return (
    <div className="App" style={{textAlign:'center'}}>
      originalArray: {originalArray}
      <br/>
      clonedArray:{clonedArray}
      <br/>
      <button onClick={() => setOriginalArray([1])}>update original</button>
    </div>
 );

}

about 4 years ago · Juan Pablo Isaza 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