🖥FrontEnd/Redux

Redux Toolkit 사용방법

hellohailie 2022. 7. 28. 22:35

 

1. Redux Toolkit 설치하기

# NPM
npm install @reduxjs/toolkit

2. package.json에서 리덕스 라이브러리 삭제하기 (Redux Toolkit에 이미 포함되어 있기 때문에 )

 

3. 리듀서 함수 만드는 곳에 slice 만들기 - createSlice

 

import { createSlice } from "@reduxjs/toolkit"; //리덕스 툴킷 시작하기 // createSlice가 createReducer보다 더 강력함

const initialState = { counter: 0, showCounter: true };

// 전역 상태의 slice를 미리 만들어놓기 // 코드를 유지보수하기 좋다.
createSlice({
  name: "counter",
  initialState: initialState,
  reducers: {
    increment(state) {
      state.counter++; // 리덕스 툴킷과 createSlice와 같은 함수를 함께 쓰면 기존 state를 바꿀 수 없다. (내부적으로 원본 state를 복제해서 원본 state가 변하지 않도록 덮어씌운다.)
    },
    decrement(state) {
      state.counter--;
    },
    increase(state, action) {
      state.counter = state.counter + action.amount;
    },
    toggleCounter(state) {
      state.showCounter = !state.showCounter;
    },
  },
});

➥ 기존에 썼던 방법보다 코드가 훨씬 짧아졌다. 

 

 

4. store가 slice를 아는 방법 & slice 사용하는 방법

 

store에 연결해주자!

const store = createStore(createSlice.reducer);

하지만 상태 slice가 많아지면서 앱의 규모가 커졌을 때, 문제가 생길 수도 있다.

왜냐하면 createStore에는 하나의 리듀서만 전달해야 하는데, slice가 여러 개라면 .reducer를 이용해 서로 다른 slice에 접근하는 리듀서도 여러 개이기 때문이다. 

 

👉 import { createStore } from "redux"를 버리고, 아래처럼 툴킷의 configureStore를 사용하면 된다. 

 

import { configureStore } from "@reduxjs/toolkit";

configureStore는 여러 개의 리듀서를 하나의 리듀서로 쉽게 합칠 수 있다. 

 

const store = configureStore({ reducer: createSlice.reducer });

정리)

// 일반 리덕스에서 store와 연결하는 방법
const store = createStore(firstReducer);

// 리덕스 툴킷 에서 store와 연결하는 방법
const store = createStore(createSlice.reducer); 

// 이걸 전역 상태를 담당하는 주요 리듀서로서 사용할 수 있다.
const store = configureStore({ reducer: createSlice.reducer }); 

// 만약 slice가 여러개인 경우
const store = configureStore({ reducer: {counter : createSlice.reducer} });

// slice가 2개 이상이라면!
const store = configureStore({
  reducer: { counter: counterSlice.reducer, auth: authSlice.reducer },
});

 

5. slice에 액션 보내는 방법

 

액션을 전달하는 것은 createSlice 가 할 수 있다. 

 

counterSlice.actions

👆 액션 생성자라고 부르고, type 프로퍼티와 액션마다 다른 고유 식별자를 가지고 있다.

 

store에서 아래처럼 export 해주고, 

export const counterActions = counterSlice.actions;

 

액션이 필요한 컴포넌트에서 작업하면 된다. 

import { counterActions } from "../store/index";

const incrementHandler = () => {
    dispatch(counterActions.increment()); // 리덕스 툴킷 사용
    //dispatch({ type: "increment" }); 일반 리덕스에서 액션을 디스패치하는 방법
  };

 

 만약 payload가 있다면?

  const increaseHandler = () => {
    dispatch(counterActions.increase(5)); // payload는 인자로 넣어주기만 하면 된다.

    //dispatch({ type: "increase", amount: 5 });
  };

그리고 store에서 payload라고 수정해주기

const counterSlice = createSlice({
  name: "counter",
  initialState: initialState,
  reducers: {
    increment(state) {
      state.counter++;
    },
    decrement(state) {
      state.counter--;
    },
    increase(state, action) {
      state.counter = state.counter + action.payload; // here!! (기존 : action.amount)
    },
    toggleCounter(state) {
      state.showCounter = !state.showCounter;
    },
  },
});

 

 

6. 리덕스가 관리하는 데이터를 사용하는 방법 = useSelector()

 

리덕스 관리 상태에서 데이터를 읽는다. 

import { useSelector } from "react-redux"; // useSelector 자동으로 상태의 일부를 선택하게 해준다.

 

👇 함수 안에서 useSelector 써주기 👇

const counter = useSelector((state) => state.counter.counter); 
const show = useSelector((state) => state.counter.showCounter);

 

(state) => state.counter 이 함수는 리액트 리덕스에 의해 실행될 것이다.

그리고 리덕스 상태를 보낸다.

그리고 이 함수로 데이터를 관리한다. 그리고 자동으로 subscrition을 설정한다.

 

 

7.  리덕스에 접근해서 리덕스 상태 바뀌게 하는 방법 = useDispatch()

import { useDispatch } from "react-redux"; //리덕스에 접근하는 방법 hook을 사용하자

👇 함수 안에서 useDispatch 써주기 👇

const dispatch = useDispatch(); // dispatch는 Redux store에 대한 action을 보낸다.

const incrementHandler = () => {
    dispatch(counterActions.increment());
    
    //dispatch({ type: "increment" }); 일반 리덕스에서 액션을 디스패치하는 방법
  };

const increaseHandler = () => {
    dispatch(counterActions.increase(5)); // payload는 인자로 넣어주기만 하면 된다.

    //dispatch({ type: "increase", amount: 5 }); 일반 리덕스에서 액션을 디스패치하는 방법
  };

const decrementHandler = () => {
    dispatch(counterActions.decrement());
    
    //dispatch({ type: "decrement" }); 일반 리덕스에서 액션을 디스패치하는 방법
  };

 

공식문서

https://redux-toolkit.js.org/

 

Redux Toolkit | Redux Toolkit

The official, opinionated, batteries-included toolset for efficient Redux development

redux-toolkit.js.org

 

 

😃 잘못된 개념 전달이 있다면 댓글 부탁드립니다. 저의 성장에 큰 도움이 됩니다🤓