Redux

이민기·2022년 2월 8일
0
post-thumbnail

Redux

  • Redux : 상태 관리 라이브러리
  • 장점
    • 상태를 예측 가능하게 만듦
    • 유지보수
    • 디버깅에 유리 (action과 state log기록시)
  • 사용 원칙
    • Single source of truth : 동일한 데이터는 항상 같은 곳에서 데이터를 가져온다
      • Store를 통해 데이터를 저장
    • State is read-only : 읽기 전용
      • 변경시 Action을 통해서만 가능
    • Change are made with pure functions : 변경은 순수 함수로만 가능
    • Redux의 state는 불변성을 지켜야한다
  • Store : 상태가 관리되는 오직 하나의 공간
    const store = createStore(rootReducer);
  • Action : JavaScript의 객체이며 Store에게 data를 운반하는 역할
    { type:ADD_TO_CART, payload: request }
  • Reducer : 현재 상태와 Action을 이용해 새로운 state를 만드는 pure function
const itemReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TO_CART:
      return Object.assign({}, state, {
        cartItems: [...state.cartItems, action.payload]
      })
    default:
      return state;
  }
}
  • Dispatch : Action을 전달하는 method이며 Reducer를 호출해 state값을 변경
  • Method
    • useSelector() : component와 state를 연결하며 store의 state의 접근을 가능하게 한다
    • useDispatch() : Action객체를 Reducer로 전달해주는 메소드
  • 비동기 처리
    • redux-thunk를 사용
        export const notify =
          (message, dismissTime = 5000) =>
          (dispatch) => {
            const uuid = Math.random();
            dispatch(enqueueNotification(message, dismissTime, uuid));
            setTimeout(() => {
              dispatch(dequeueNotification());
            }, dismissTime);
          };
profile
블로그를 옮기는 중입니다. https://min71.dev

0개의 댓글