reactjs / reactjs/react.dev

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

Open
#5,597 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked React documentation section, “Updating a nested object,” and review the current spread-operator example alongside the structuredClone() proposal. Done means the section clearly presents the chosen update approach and avoids misleading readers about shallow versus deep copying.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.