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

167
Views
Do I need to clone props before using/mutating it in React?

Imagine a component has props and the props have nested objects and arrays. In the child component, if I need to copy to props.nestedObject or props.myArrays to state. Is shallow copy OK?

const [obj, setObj] = useState(props.nestedObject)

Or deep copy?

const [obj, setObj] = useState(_.cloneDeep(props.nestedObject))

The reason why I am asking this is that, normally, I use cloneDeep or Immutable.js to not worry about object references. But I don't know whether React does something behind the scenes to break object reference.

PS: _.cloneDeep is a lodash function.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

react doesn't break object reference. here is an example:

stackblitz.com playground example

I used Object.is() to compare the original object and the object returned from the useState() hook. As you can see, these objects are the same, so react does't apply any kind of cloning

about 4 years ago · Santiago Trujillo Report

0

You can set up an initial state for the useState hook without it being updated

const [obj, setObj] = useState(() => props.nestedObject)

That is what you were looking for

about 4 years ago · Santiago Trujillo 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!