Redux Toolkit (리덕스 툴킷)과 createSlice()

Ahri·2022년 2월 7일
0

Redux Toolkit(리덕스 툴킷)이란?

  • Redux 를 더 쉽게 사용하기 위한 도구
  • 기존 Redux의 여러 문제점을 보완해줌

Redux 의 문제점

  1. 무수한 보일러플레이트 코드가 필요함.
    액션 타입, 액션 생성 함수, 액션별 리듀서를 각각 정의 하는 방식

  2. 리덕스 스토어 환경 설정 복잡함
    상태관리를 위해 만들어야 하는 파일이 많고 복잡함

  3. 패키지를 많이 추가해야 함

--> Redux Toolkit은 보일러플레이트 코드를 최소화하고 하나의 파일 안에 정의할 수 있도록 하였음

[ 기존 예시 ]

  1. 액션 타입
export type StudyState = {
  startStudyTime: number|null,
  studyTime: number|null,
}
export type StudyAction = ActionType<typeof actions>
  1. 액션 생성 함수
export const
  START_STUDY = 'study/START_STUDY',
  END_STUDY = 'study/END_STUDY'
 
export const startStudy = createAction(START_STUDY, action => (startStudyTime: number) => action(startStudyTime))
export const endStudy = createAction(END_STUDY, action => (studyTime: number) => action(studyTime))
  1. 액션 리듀서
//3-1. 초기화
const initialState: StudyState = {
  startStudyTime: null,
  studyTime: null,
}
 
export default createReducer<StudyState, StudyAction>(initialState, {
  [START_STUDY]: (state, action) => {
    const startStudyTime: number = action.payload

    return produce<StudyState>(state, draft => {
      draft.startStudyTime = startStudyTime
      draft.studyTime = null
    })
  },
  [END_STUDY]: (state) => {
  const studyTime: number = action.payload
  
    return produce<StudyState>(state, draft => {
      draft.studyTime = studyTime
      draft.startStudyTime = null
    })
  }
})
  1. 스토어별 취합
export { default } from './reducer';
export * from './actions';
export * from './types';

Redux Toolkit의 createSlice()

액션 타입, 액션 생성 함수, 액션별 리듀서, 취합 파일 등을 하나의 파일로 통합할 수 있게 함

  • createSlice에 선언된 슬라이스 이름을 따라서 리듀서와 액션 생성자, 액션 타입 자동 생성
  • 따로 createAction, createReducer를 작성할 필요 없음
//1. 액션 타입
export type StudyState = {
  startStudyTime: number|null,
  studyTime: number|null,
}

//3-1. 초기화
const initialState: StudyState = {
  startStudyTime: null,
  studyTime: null,
}


const studySlice = createSlice({
    name: 'study', // 2. 액션 생성 함수의 앞에 부분. 'study/START_STUDY' 의 study
    initialState,
    reducers: { //2+3. 액션 생성과 리듀서를 한번에 함수로 정의
        startStudy(state, action: PayloadAction<number>) {
            const startStudyTime: number = action.payload
 
            state.startStudyTime = startStudyTime
            state.studyTime = null
        },
        endStudy(state, action: PayloadAction<number>) {
            const studyTime: number = action.payload
 
            state.studyTime = studyTime
            state.startStudyTime = null
        }
    }
})
 
export default studySlice.reducer
export const { startStudy, endStudy } = studySlice.actions

그 외의 더 많은 리덕스 툴킷의 유용한 API 를 보고 싶다면, [Redux Toolkit (리덕스 툴킷)은 정말 천덕꾸러기일까?] 를 참고하세요:)

0개의 댓글