Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

239
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda