react.dev icon indicating copy to clipboard operation
react.dev copied to clipboard

[Beta] Using the structuredClone() for updating a nested object

Open IvanMilosav opened this issue 2 years ago • 2 comments
trafficstars

https://beta.reactjs.org/learn/updating-objects-in-state#updating-a-nested-object

I think that deep cloning object with structuredClone() and putting the clone into setPerson() is better solution for the problem than using the spread operator.

The the example that was provided can easily be changed this way:

personCopy = structuredClone(person);
personCopy.artwork.city = "New Delhi";
setPerson(personCopy);

This can help avoiding the mistake when spread operator is used to deep clone objects. See example below:

const original = { a: { b: 1 } };
const falseCopy = { ...original };

falseCopy.a.b = 2;

console.log(falseCopy); // logs {a: {b: 2}}
console.log(original); // also logs {a: {b: 2}}

I am sorry if I have failed to follow contributing guidelines. I am aware that the second example is not the best representation of my point.

IvanMilosav avatar Feb 16 '23 12:02 IvanMilosav

Using a library like Immer would be better since structuredClone creates a deep copy of the whole object unlike Immer which does structural sharing to increase performance.

yousefelgoharyx avatar Feb 17 '23 12:02 yousefelgoharyx

I agree, but it requires additional library.

IvanMilosav avatar Feb 17 '23 12:02 IvanMilosav