Redux 사용 정리

박용희·2023년 10월 31일
0

Redux 사용 정리

예제) Count값을 변경 해주는 버튼

1. createSlice

// Slice.ts
import { createSlice, PayloadAction } from "@reduxjs/toolkit";

// 상태의 초기 상태 정의
const initialState: { value: number } = { value: 0 };

// 리듀서 및 액션 생성기 생성
const counterSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload;
    },
  },
});

// 액션 생성자 내보내기
export const { increment, decrement, incrementByAmount } = counterSlice.actions;

// 리듀서 내보내기
export default counterSlice.reducer;

initialState: 초기 상태값을 정의하고 타입 지정(ts를 사용할 시 )

reducers: 해당 객체내에서 다양한 액션에 대해 함수 정의
만약, 함수에 파라미터값을 넣을려면 action으로 파라미터 값을 받고 action.payload를 사용한다.
타입은 PayloadAction<타입지정>을 사용하고 import를 해서 사용

export를 사용하여 액션 함수와 리듀서를 내보낸다.

2. configureStore

import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./counterSlice";

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

export type RootState = ReturnType<typeof store.getState>;

export default store;

state 관리하는 것들을 보관하는 파일

store에 configureStore을 사용하여 해당 reduce을 정리한다.

export type RootState = ReturnType<typeof store.getState>;

을 사용하여 ReturnType을 추론하여 RootState에 타입을 보관한다.

이렇게하면 다른 컴포넌트에서 import를 할 때, useSelector의 state를 쉽게 타입을 지정할 수 있다.

3. 해당 컴포넌트 사용

//Counter.tsx
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { increment, decrement, incrementByAmount } from "./counterSlice";
import { RootState } from "./store";
import { Dispatch } from "redux";

const Counter: React.FC = () => {
  const dispatch: Dispatch = useDispatch();
  const count = useSelector((state: RootState) => state.counter.value);

  return (
    <div>
      <h2>카운터</h2>
      <p>: {count}</p>
      <button onClick={() => dispatch(increment())}>증가</button>
      <button onClick={() => dispatch(decrement())}>감소</button>
      <button onClick={() => dispatch(incrementByAmount(5))}>5 증가</button>
    </div>
  );
};

export default Counter;

컴포넌트에서 사용을 할 때, useDispatch와 useSelector을 import해야한다

0개의 댓글