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

256
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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