🔱 수업 https://nomadcoders.co/react-masterclass/lobby 을 듣다가 6.14, 6.15장 immutability part 를 듣다가 아래 slice 통해서 값을 교체하는 방식으로 진행하는 것을 보고 왜 state가 immutable 해야 하는지 찾아보았다.
setToDos((oldTodos) => {
const targetIndex = oldTodos.findIndex(toDo => toDo.id === id);
const oldTodo = oldTodos[targetIndex];
const newTodo = {text, id, category: name as any};
return [
...oldTodos.slice(0, targetIndex),
newTodo,
...oldTodos.slice(targetIndex + 1),
];
})
1. immutable의 의미
- 데이터가 절대로 바뀌지 않아야 한다는 것은 아니다.
- 예를 들어, 배열을 mutate한다 했을때,
> 원래 배열의 복사본을 만든다.
> 복사본에 변경사항을 적용한다.
> 원래 배열을 변경된 복사본으로 교체한다.
2. 왜 react가 immutable한지 ?
- 부모 컴포넌트가 re-rendering 될 때 new value 가 필요하기 때문
> 만약 3개의 값이 있는 array에서 4번째 값을 넣는다고 해서, reference가 변경하지 않는다.
참고 문헌 >
https://reacttraining.com/blog/state-in-react-is-immutable
반응형