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



Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matteo Tommasi
Solution 2 Jhonatan