[react] Redux Toolkit 사용(1) createSlice

Subin Ryu·2024년 10월 27일
post-thumbnail

Redux Toolkit 사용(1) createSlice

  1. 개념
  2. 목적
  3. 원리
  4. 사용방법

개념

  • 상태관리를 위해 만들어진 Redux의 공식 라이브러리

목적

  • Redux를 더 쉽게 설정하고 관리
  • 기존 Redux에서 자주 사용되는 반복적이고 복잡한 코드 패턴을 줄여줌 (보일러플레이트 코드를 최소화)

*보일러플레이트 코드: 복잡한 설정 과정이나 반복적으로 필요한 초기 코드

원리

  • 슬라이스(Slice) 관리: createSlice를 통해 상태, 리듀서, 액션 생성자를 하나의 슬라이스로 통합하여, 반복적인 코드 없이도 상태 관리가 가능

  • 주요 속성 - name, initialState, reducers, extraReducers

    • name: 슬라이스의 이름으로, 액션 타입을 생성할 때 사용
    • initialState: 슬라이스의 초기 상태를 설정
    • reducers: 동기적으로 상태를 변경하는 함수들을 정의하고 각 함수는 자동으로 액션 생성자를 만듦
    • extraReducers: 비동기 액션이나 외부 액션을 처리하는 리듀서를 정의
  • createSlice로 생성된 슬라이스 객체의 주요 속성 - name, reducer, actions, caseReducers

    • name
      슬라이스의 이름을 나타내며, 주로 action 타입을 생성할 때 사용
      이 name 속성은 액션 타입이 sliceName/actionName 형식
      (예 'product/getSingleProduct')

    • reducer

      • 슬라이스에서 생성한 리듀서 함수
      • reducers와 extraReducers에서 정의된 모든 리듀서 함수가 결합되어 있음
    • actions

      • reducers에서 정의한 각각의 리듀서 함수에 대해 자동으로 액션 생성 함수를 만들어주는 객체
      • 슬라이스에서 정의한 리듀서 함수 이름을 키로 사용하여 액션 생성자 함수를 매핑
      • 예를 들어 getSingleProduct라는 리듀서를 만들었다면 productSlice.actions.getSingleProduct(payload)로 호출하여 액션 객체를 생성
    • caseReducers

      • reducers와 extraReducers에서 정의된 리듀서 함수들이 포함된 객체
      • 슬라이스 내에서 액션별로 어떤 리듀서가 사용될지를 매핑해둔 속성으로, reducer 함수에서 state와 action에 따라 적절한 케이스를 처리하는 데 사용됨
      • 다만 caseReducers는 주로 내부적으로 참조됨

사용방법

  1. 설치
    npm install @reduxjs/toolkit
    // 기존 dedux 제거(option)
    npm uninstall redux
  2. 기존 reducer.js 파일 변경
  • reducer 함수 생성해서 action type 경우에 따라 state 결과 반환
    -> createSlice 이용해 action에 대한 reducer 함수에서 state 결과 반환
  • 코드가 간결해짐
  • 기존 방식 사용처럼 return에서 변하지 않는 값 {...state} 안해줘도 됨
import {createSlice} from "@redux/toolkit"

let initialState = {
  productList: [],
  productDetailList: null,
};

// createSlice 3가지요소 name, initialState,reducers
// action 이름을 만드는데 name이라는 키가 쓰임
const productSlice = createSlice({
  name:"product",
  initialState,
  reducers:{
    // 전체 상품보여주는 리듀서
    getAllProducts(state,action){
      state.productList = action.payload
    },
    // 상품 한개만 보여주는 리듀서
    getSingleProduct(state,action){
      state.productDetailList = action.payload
    }
  }
})

// actions에 Slice에서 정의한 action들이 담겨있음
export const productActions = productSlice.actions
// reducer에 모든 reducers들이 나
export default productSlice.reducer;
// createSclice 속성
// actions, caseReducers,getInitialState,reducer
  1. 기존 store.js 파일 변경 (createStore -> configureStore)
  • createStore에서는 역할에 따라 나눈 reducer 파일들을 하나로 통합 해주는 파일을 생성해 createStore 파라미터값으로 넣었지만,
    condigureStore에서는 역할에 따라 나눈 reducer를 바로 적용시킬 수 있음
import productReducer from './reducer/productReducer';
import authenticateReducer from './reducer/authenticateReducer';
import { configureStore } from '@reduxjs/toolkit';

// 여러 reducer들 통합파일 안만들어줘도 됨
// thunk, applyMiddleware, composeWithDevTools 따로 설정 안해줘도 됨
// 모두 자동셋업 되어 있음
let store = configureStore({
  reducer: {
    auth: authenticateReducer,
    product: productReducer,
  },
});
export default store;
  1. 기존 action.js 파일 변경 (dispatch 내용 변경)
  • 기존방식 {type:"action_이름", payload:"파라미터"}
  • toolkit방식 reducer파일.reducer함수(파라미터)
  • 기존보다 간단하게 dispatch 가능
import { productActions } from '../reducer/productReducer';

function getProducts(){
 // data 있다고 가정
dispatch(productActions.getAllProducts(data));
  };
}

function getProductDetail() {
  return async (dispatch, getState) => { 
    dispatch(productActions.getSingleProduct(data));
  };
}

export const productAction = { getProducts, getProductDetail };
profile
개발블로그입니다.

0개의 댓글