Redux Toolkit 사용하기

njn613·2023년 7월 5일
0

react

목록 보기
1/8

redux toolkit

"전역" 상태를 관리하는 데 도움을 주는 Redux

  • Redux store 구성이 너무 복잡합니다.
  • Redux가 유용한 작업을 수행하려면 많은 패키지를 추가해야 합니다.
  • Redux는 많은 양의 Boiler Plate Code를 필요로 합니다.

이런 Redux의 고충을 해결하기 위해 만들어진 Redux toolkit


패키지 추가하기

npm install @reduxjs/toolkit
#React bindings
npm install @reduxjs/toolkit react-redux

#or

yarn add @reduxjs/toolkit
#React bindings
yarn add @reduxjs/toolkit react-redux

API

configureStore()

  • 기존의 store
import { createStore } from "redux";
import { combineReducers } from "redux";
import counter from "src/redux/modules/counter";

const rootReducer = combineReducers({
  counter,
});

const store = createStore(rootReducer);
export default store;
  • configure store 사용하기
import { configureStore } from "@reduxjs/toolkit";
import counter from "src/redux/modules/counterSlice";
import todos from "src/redux/modules/todosSlice";

const store = configureStore({
  reducer: { counter: counter, todos: todos },
});

export default store;

createSlice()

  • 기존의 Reducuer
// Action Value
const ADD_NUMBER = "ADD_NUMBER";
const MINUS_NUMBER = "MINUS_NUMBER";

// Action Creator
export const addNumber = (payload) => {
  return {
    type: ADD_NUMBER,
    payload,
  };
};

export const minusNumber = (payload) => {
  return {
    type: MINUS_NUMBER,
    payload,
  };
};

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

// Reducer
const counter = (state = initialState, action) => {
  switch (action.type) {
    case ADD_NUMBER:
      return {
        number: state.number + action.payload,
      };
    // [퀴즈 답]
    case MINUS_NUMBER:
      return {
        number: state.number - action.payload,
      };
    default:
      return state;
  }
};

// export default reducer
export default counter;
  • create slice 사용하기
import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  number: 0,
};

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

    minusNumber: (state, action) => {
      state.number = state.number - action.payload;
    },
  },
});

export const { addNumber, minusNumber } = counterSlice.actions;
export default counterSlice.reducer;

0개의 댓글