useSelector 최적화

김형민·2021년 5월 31일
0

배열이 매번 생성이 되기 때문에 안에 있는 값들이 변경되지 않더라도, redux에서 action이 처리될 때 마다 불필요하게 컴포넌트가 랜더링될 수 있다는 단점이 존재했었다.

useSelector로 가져온 상태값들이 변하지 않는다면 굳이 이 값들을 다시 가져올 필요하 없다고 생각했다!

수정전의 코드

 const preview = useSelector((state) => state.image2.preview);
 const is_file = useSelector((state) => state.image2.file);
 const profile = useSelector((state) => state.profile.user);
 const onlyImg = useSelector((state) => state.image2.image);
 const is_category = useSelector((state) => state.category.select_category);

수정후의 코드
하나씩 선언해서 가져오던 방식을 배열형식으로 가져오는 것으로 수정했고 두번째 인자로
shallowEqual을 넣어줬다

  //shallowEqual을 써줘서 렌더링 될때마다 useSelector로 가져온 값을 비교하고 같으면
  const [preview, is_file, profile, onlyImg, is_category] = useSelector(
    (state) => [
      state.image2.preview,
      state.image2.file,
      state.profile.user,
      state.image2.image,
      state.category.select_category,
    ],
    shallowEqual
  );

useSelector 훅의 두 번째 매개변수는 컴포넌트 렌더링 여부를 판단하는 역할을 한다. 이 매개변수가 없는 경우 참조 값만 비교하는 단순 비교 함수가 사용됨. 따라서 선택자 함수가 객체 리터럴을 반환하면 컴포넌트가 불필요하게 렌더링되는 문제가 발생. 이 때 react-redux의 shallowEqual 함수를 이용할 수 있다.

profile
항해 중인 개발자

0개의 댓글