12-4: setState(), useState() 사용법

JJeong·2021년 2월 24일
0

setState()를 사용할 때 state의 일부만 넣어서 사용해도 값이 변경될까?

useState()로 다중 객체의 값을 변경할 때 주의점

Generally you should watch out for deeply nested objects in React state. To avoid unexpected behavior, the state should be updated immutably. When you have deep objects, you end up deep cloning them for immutability, which can be quite expensive in React. Why?

Once you deep clone the state, React will recalculate and re-render everything that depends on the variables, even though they haven't changed!

So, before trying to solve your issue, think how you can flatten the state first. As soon as you do that, you will find beautiful tools that will help dealing with large states, such as useReducer().

In case you thought about it, but are still convinced you need to use a deeply nested state tree, you can still use useState() with libraries like immutable.js and Immutability-helper. They make it simple to update or clone deep objects without having to worry about mutability.

리액트 state를 깊고 복잡하게 만드는 것을 피해야 합니다. 항상 state를 변경할 때는 불변성을 유지해야 하기 때문입니다. 이를 위해서 깊은 복사가 진행되어야 하고 해당 변수와 관련이 있는 모든 컴포넌트들이 리렌더링됩니다. 전혀 바뀐 게 없는데도요!

따라서 우선 리액트 state를 얕게 만드는 것을 고민해야 합니다. useReducer()가 멋진 해결책이 되어줄 것입니다. 이후 복잡한 state를 useState()를 사용해야 한다면 immutable.js나 Immutablility-helper와 같은 불변성을 위한 툴을 이용하면 됩니다. 이들은 수정을 간단하게 만들어주거나 mutability에 대한 걱정 없이 깊은 복사를 할 수 있게 도와줍니다.

0개의 댓글