January 6, 2022

#4 REDUX TOOLKIT (BONUS)

#4.0 Redux Toolkit (02:17)

redux를 사용하면서 boiler plate code (상용구 코드) 가 필요하다

yarn add @reduxjs/toolkit

#4.1 createAction (06:16)

const addToDo = createAction('ADD'); // 새로운 부분
const deleteToDo = createAction('DELETE'); // 새로운 부분

const reducer = (state = [], action) => {
  switch (action.type) {
    case addToDo.type: // 새로운 부분

			// action.text -> action.payload
      return [{ text: action.payload, id: Date.now() }, ...state];
    case deleteToDo.type: // 새로운 부분

			// action.id -> action.payload
      return state.filter((toDo) => toDo.id !== action.payload);
    default:
      return state;
  }
};

Untitled

action을 따로 정의하지 않아도 되서 최적화가 되었다

#4.2 createReducer (07:52)

createReducer 특징

  1. 더이상 switch가 필요 없다
  2. state를 mutate(복제)하기 쉽다
  3. 두가지 방법이 존재
    1. state 를 직접 return
    2. state mutate (push, ..)

Untitled

const reducer = createReducer([], {
  [addToDo]: (state, action) => {
    state.push({ text: action.payload, id: Date.now() });
  },
  [deleteToDo]: (state, action) =>
    state.filter((toDo) => toDo.id !== action.payload),
});

#4.3 configureStore (07:13)