-
[에러일지] useSelector.js:99 Selector unknown returned the root state when called. This can lead to unnecessary rerenders.Selectors that return the entire state are almost certainly a mistake, as they will cause a rerender whenever *anything* in st..에러일지 2023. 11. 22. 23:50
리덕스로 프로젝트를 개발하는 중에 워닝 에러가 떴다
useSelector.js:99 Selector unknown returned the root state when called. This can lead to unnecessary rerenders.
Selectors that return the entire state are almost certainly a mistake, as they will cause a rerender whenever *anything* in state changes.무슨내용인지 번역기를 돌려 보았다.
useSelector.js:99 Selector unknown이 호출 시 루트 상태를 반환했습니다. 이로 인해 불필요한 재렌더가 발생할 수 있습니다.
전체 상태를 반환하는 선택기는 상태가 변경될 때마다 *무엇이든* 재귀환을 야기하기 때문에 거의 확실히 실수입니다.useSelector를 사용할 때 불필요한 재렌더링이 발생한다고 하였다.
그리고 이 에러가 뜨면서 useSelector로 불러온 state가 undefined로 출력된다.
구글에 검색해 보았다.
에러 메시지로 검색하니 나오지 않았다.
useSelector가 undefined라고 검색하니 나왔다.
결론은 구조분해 할당을 사용해서 생기는 에러였다.
내가 사용한 코드
const {detail} = useSelector((state) => state);
rootReducer에 reducer들이 Object형태로 담게있길레 구조분해 할당으로 필요한 reducer만 가져와 사용했는데 이것이 문제었다.
위 에러를 이해하기 위해서는 useSelector가 어떻게 작동하는지 알아야 한다.
useSelector는 컴포넌트가 렌더링 되거나 action이 dispatch될 때 동작한다.
useSelector는 기존의 state와 변경된 state를 비교하여 값이 다르면 컴포넌트를 리렌더링 한다.
useSelector의 state는 객제(Object)이다 객체는 값을 그데로 저장하는 것이 아니라 값이 저장된 '메모리 주소' 를 저정한다.
예를 들어 const { detail } = useSelector((state) => state);은 const state = useSelector((state) => state); 의 state.detail과 같다
이렇게 되면 state.detail은 객체 이기 때문에 state.detail의 값은 원시적인 타입의 값이 아니라 메모리 주소를 갔고있는 것이다.
그래서 state.detail의 state값이 일부가 변경되더라도 state의 일부만 변경되는 것이 아니라 매모리 주소가 새로할당되어 저장되기 때문에 전혀 다른 값으로 인식한다.
그래서 위와 같이 제렌더링이 일어난다는 워닝이 뜬것이다.
일부만 바뀌는 것으로 인식해야 하는데 메모리주소가 새로 할당되어 전체가 바뀌는것으로 인식하니 불필요한 재렌더링이 발생하는 것이다.
해결 뱡법
useSelector를 여려번 쓰면 된다.
const users = useSelector((state) => state.users); const detail = useSelector((state) => state.detail);
이렇게 사용하면 코드는 길어지지만 원시적인 타입의 값을 비교하기 때문에 제렌더링이 일어나지 않는다.
이방법은 redux공식문서에서도 권장하는 방식이다.
여기서 중요한 것은 useSelector를 여러번 사용하는 것이 아니라 각각의useSelector가 반환하는 값이 원시 타입 값 이라는 것이다.
참고 블로그
https://chamdom.blog/useselector-optimization/
Redux의 useSelector 최적화 하기
들어가며 지금까지 Redux toolkit을 사용하면서 useSelector 를 잘못 사용하고 있다는 것을 알게되었다. 다음과 같이 구조 분해 할당을 사용하여 useSelec…
chamdom.blog
redux 공식문서
https://redux.js.org/tutorials/fundamentals/part-5-ui-react#using-multiple-selectors-in-a-component