불변성의 중요성

기존의 값을 직접 수정하지 않으면서 새로운 값을 만들어 내는 것을 '불변성을 지킨다' 라고 한다.
const array = [1, 2, 3, 4, 5]; const nextArrayBad = array; nextArrayBad[0] = 100; console.log(array === nextArrayBad); // true 완전이 같은 배열이기 때문에 const nextArrayGood = [...array]; // 배열 내부의 값을 모두 복사 nextArrayGood[0] = 100; console.log(array === nextArrayGood); // 다른 배열이기 때문에 false const object = { foo: "bar", value: 1, }; const nextObjectBad = object; // 객체가 복사 되지 않고, 똑같은 객체를 가리킨다. nextObjectBad.value = nextObjectBad.value + 1; console.log(object === nextObjectBad); // 같은 객체이기 때문에 true const nextObjectGood = { ...object, // 기존에 있던 내용을 모두 복사해서 넣는다. value: object.value + 1, // 새로운 값을 덮어 쓴다. }; console.log(object === nextObjectGood); // 다른 객체이기 때문에 false
불변성이 지켜지지 않으면, 객체 내부의 값이 새로워져도 바뀐 것을 감지하지 못한다.
그래서 React.memo에서 서로 비교하여 최적화하는 것이 불가능하다.