Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

251
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!