개인공부/TIL(Today I Learned)

TIL 77일차_Redux hooks: useSelector(), useDispatch()

soon327 2021. 4. 5. 21:22

Redux의 state와 React의 component를 연걸하는 방법에는 다음 두가지 방법이 있다.

  1. connect parameter를 통해 mapStateToProps, mapDispatchToProps와 같은 메소드를 이용하는 방법
  2. Redux hooks의 useSelector(), useDispatch() 메소드를 이용하는 방법

이 중, Redux hooks가 좀더 최근에 나온 방법이고 직관적인 방법이다.

useSelector()

useSelector()는 컴포넌트와 state를 연결하는 역할을 한다.
컴포넌트에서 useSelector메소드를 통해 store의 state에 접근할 수 있다.

const { postList } = useSelector(store => store.post.postList);

selector는 컴포넌트가 렌더링 될 때 호출된다.
그리고 useSelector는 리덕스의 store를 subscribe 하는 구조이기 때문에
action이 dispatch되면 마찬가지로 selector를 돌린다.

그리고 함수가 처음 렌더링 될 때는 selector가 무조건 호출 되지만,
action이 store에 dispatch될 때는 그 결과가 현재 selector가 호출한 결과와 다른 경우에만 re-render 된다.

이에 따르면, useSelector가 객체를 리턴하는 경우,
항상 새로운 객체로 판단할 것이고, 그런 경우 객체의 필드값이 같더라도 무조건 re-render 된다.

이런 경우를 위해서, react-redux에서 제공하는 shallowEqual 함수가 있다.
문서가 말하는 대로라면, shallowEqual을 사용하면 객체를 리턴하는 경우의 성능상의 이슈를 최소화 할 수 있다고 생각된다.
제공해주는 예시는 다음과 같다.

import { shallowEqual, useSelector } from "react-redux";

// later
const selectedData = useSelector(selectorReturningObject, shallowEqual);

useDispatch()

useDispatch()는 action 객체를 reducer로 전달해주는 메소드이다.
action이 일어날만한 곳은 클릭 등의 이벤트가 일어나는 컴포넌트인 경우가 대부분이다.

const dispatch = useDispatch();

일반적인 store.dispatch()처럼 dipatch()를 사용하면 된다.

참고: CH DEVLOG