개발/리액트

react. state가 immutable해야 하는 이유

ttoance 2023. 8. 15. 07:35

🔱 수업 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

 

State in React is Immutable

tldr; When you set state in React, a new value must be passed or React will bail-out and not *re-render your component. React uses something similar to === to compare the old and new state to see if they're the same. They say in docs they use Object.is() i

reacttraining.com

https://scoring.tistory.com/entry/React-%EB%A6%AC%EC%95%A1%ED%8A%B8%EC%97%90%EC%84%9C-%EB%B6%88%EB%B3%80%EC%84%B1%EC%9D%84-%EC%A7%80%ED%82%A4%EB%8A%94-%EC%9D%B4%EC%9C%A0

 

[React] 리액트에서 불변성을 지키는 이유

리액트에서 불변성을 지키는 이유 불변성이란 사전적 의미로 값이나 상태를 변경할 수 없는 것을 의미한다. React가 불변성을 지키는 이유는 부모 컴포넌트가 re-rendering 되거나 State, Props 에 변화

scoring.tistory.com

 

반응형