React parent prop with nested array is mutated by spread copied state variable?

Consider the following:

type ObjectWithNestedArray = {
  array: { name: string }[];
};

const App = () => <Parent />;

const Parent = () => {
  const objWithNestedArray = { array: [{ name: "A" }] };
  return <Child objWithNestedArray={objWithNestedArray}></Child>;
};

const Child = (props: { objWithNestedArray: ObjectWithNestedArray }) => {
  const [stateObjWithNestedArray, setStateObjWithNestedArray] = useState<ObjectWithNestedArray>();
  const [count, setCount] = useState<number>(0);

  const onChange = () => {
    if (stateObjWithNestedArray) {
      //const copyOfObj = structuredClone(stateObjWithNestedArray) as ObjectWithNestedArray;
      const copyOfObj = { ...stateObjWithNestedArray };
      copyOfObj.array[0].name = "B";
    }
    setCount(count + 1);
  };

  useEffect(() => {
    if (props.objWithNestedArray) {
      setStateObjWithNestedArray((current) => props.objWithNestedArray);
    }
  }, [props.objWithNestedArray]);

  return (
    <div>
      <pre>obj={JSON.stringify(props.objWithNestedArray, null, 2)}</pre>
      <button onClick={() => onChange()}>Click me</button>
    </div>
  );
};

When I render my App I get:

propsFormDef={
  "array": [
    {
      "name": "A"
    }
  ]
}

However when I click the button it is somehow modifying the passed in property:

propsFormDef={
  "array": [
    {
      "name": "B"
    }
  ]
}

If I modify the line in the onChange to be the commented out one:

const copyOfObj = structuredClone(stateObjWithNestedArray) as ObjectWithNestedArray;

Then the prop value doesnt change.

Can someone explain how modifying a spread copy of a state variable changes the passed in property when there are no callbacks and props are supposed to be immutable in React?

Is it because the array in the passed in prop is passed by reference and similarly, the spread copy copies the reference so that when I change a value in that array, I’m actually modifying the original prop array’s memory location?

1

Let us discuss the same.

const obj = {
  array: [{ name: 'A' }],
};

const copyOfObj = { ...obj }; // spread operator in use

Observations:

a) The following check results in a false value. It shows that original and the newly created object by copying are entirely two different objects.

console.log(obj === copyOfObj);  // false

b) The following check results in true value. It shows although the original and the newly created object are entirely two different objects, the array object referenced in both of the two objects are the same.

console.log(obj.array === copyOfObj.array); // true

c) Therefore, the below assignment will mutate both objects, it means it will mutate the original object as well. Please see below the output.

copyOfObj.array[0] = 'B';

console.log(obj);       // {  array: [{ name: 'B' }], };
console.log(copyOfObj); // {  array: [{ name: 'B' }], };

Solution:

Instead of the spread operator, the function structuredClone may be used.

Please see below an example.

const obj = {
  array: [{ name: 'A' }],
};

const copyOfObj = structuredClone(obj);

Observations:

a) The following check results in a false value. It shows two objects are different.

console.log(obj === copyOfObj);  // false

b) The following check results in a false value. The array objects referenced in both of the two objects are not the same, it is different.

console.log(obj.array === copyOfObj.array); // false

c) Therefore, the below assignment will mutate not mutate the original object.

copyOfObj.array[0] = 'B';

console.log(obj);       // {  array: [{ name: 'A' }], };
console.log(copyOfObj); // {  array: [{ name: 'B' }], };

0

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật