Skip to content

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

Open
@IvanMilosav

Description

@IvanMilosav

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions