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

252
Vistas
Child changes the value in parent

I pass an array from the parent, in the child I receive it through a props and pass it to the state. After that, I need to add a field to the array, I do this in useEffect. But as soon as this goes through, the data also changes in the parent. Why is this happening?

Parent:

<IncomeDrawer values={selectRowData}/>

Child:

const [values, setValues] = useState(props.values);

useEffect(() => {
  let newData = values.docSubs;

  function updateTreeTable(data) {
    for (let i = 0; i < data.length; i++) {
      data[i] = { ...data[i], recordIndex: recordIndex };
      recordIndex++;
      if (data[i].hasOwnProperty('children')) {
        updateTreeTable(data[i].children);
      }
    }

  };
  updateTreeTable(newData);

  setValues({ ...values, docSubs: newData })

}, [])
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I think the solution might be to use the spread operator like that:

const [values, setValues] = useState([...props.values]);

As pointed out by Khabir the problem is in the props reference.

P.S. Sorry, I didn't comment, but I don't have the necessary reputation.

about 4 years ago · Juan Pablo Isaza Denunciar

0

When you pass props into your child component, it passes the reference. so if you change the value in child component which came from parent, it will change in both child and parent.

To avoid this, you need to clone your props value into your child component before changing it.

In React, actually in JavaScript, there are many ways to clone object/array

Using slice function

const [values, setValues] = useState(props.values.slice());

Using Spread Operator

const [values, setValues] = useState([...props.values]);

Using JSON.parse and JSON.stringify function

const [values, setValues] = useState(JSON.parse(JSON.stringify(props.values));

There are some other ways to clone your array. you google it if you want to know.

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