Recent Posts
Recent Comments
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Today
Total
관리 메뉴

DH의 개발 공부로그

[Redux] Redux Toolkit - configureStore, createSlice 사용하기 본문

Redux

[Redux] Redux Toolkit - configureStore, createSlice 사용하기

DeveloperDH 2023. 3. 22. 20:28
728x90

Redux Toolkit

리덕스 툴킷이란 리덕스의 여러가지 불편했던 부분들을 리덕스 팀에서 개선하고, 더욱 효율적으로 리덕스를 이용할 수 있도록 만든 도구 모음입니다.
그리하여 리덕스 공식문서에서는 러덕스 툴킷이 필수는 아니지만 사용하기를 적극 권장하고 있습니다.

Redux Toolkit의 장점

  1. 초기 설정이 간편해졌습니다.
  2. 리덕스 툴킷 내부에 설치되어있어서 더이상 다양한 패키지들를 설치 하지 않아도 됩니다. (redux devtool, immer, thunk 등등)
  3. 반복되는 코드가 많아서 코드가 복잡해졌던 부분이 개선되었습니다.
  4. 툴킷에서는 더이상 불변성을 신경쓰지 않아도 됩니다.

코드 비교 및 사용 방법

1. createSlice

기존 리덕스에서는 action value, action creator, initial state, reducer를 개별적으로 작성을 해서 사용하기 때문에 복잡한 부분이 있었습니다.
그래서 리덕스 툴킷에서는 해당 코드들을 createSlice에 합쳐서 작성을 하여 코드의 복잡한 부분들을 개선했습니다.

// 기존 리덕스

//action value
const ADD = "ADD";

//action creator
export const addNumber = (payload) => {
  return {
    type: ADD,
    payload,
  };
};

// Initial State
const initialState = {
  number: 0,
};

// Reducer
const counter = (state = initialState, action) => {
  switch (action.type) {
    case ADD:
      return { ...state, number = state.number + action.payload };
    default:
      return state;
  }
};

// export default reducer
export default counter;
// 리덕스 툴킷
import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  number: 0,
};

const counterSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    add: (state, action) => {
      state.number = state.number + action.payload;
    }
  },
});

export const { add } = counterSlice.actions;
// 액션크리에이터는 컴포넌트에서 사용하기 위해 export
// dispatch(add(1)) 이런식으로 사용 -> dispatch(counterSlice.actions.add(1)) 형태

// reducer 는 configureStore에 등록을 위해 export default 합니다.
export default counterSlice.reducer;

2. configureStore

// 리덕스
import { createStore } from "redux";
import { combineReducers } from "redux";
import counter from "../modules/counter";

const rootReducer = combineReducers({
  counter,
});

export const store = createStore(rootReducer);
// 리덕스 툴킷
import { configureStore } from '@reduxjs/toolkit'
import counterSlice from '../module/counterSlice' // import counterSlice.reducer

export const store = configureStore({
  reducer: {
    counter: counterSlice,
    // 모듈(Slice)이 여러개인 경우 reducer 안에 각 모듈의 slice.reducer를 추가
  }
})
728x90
Comments