Frontend Study

Redux #2

jimmmy_jin 2025. 1. 6. 07:37
import { configureStore, createSlice } from "@reduxjs/toolkit";

const counterSlice = createSlice({
  name: "counter",
  initialState: { counter: 0 },
  showCounter: true,
  reducers: {
    increment(state) {
      state.counter = state.counter + 1;
    },
    decrement(state) {
      state.counter = state.counter - 1;
    },
    increase(state, action) {
      state.counter = state.counter + action.payload;
    },
    toggleCounter(state) {
      state.showCounter = !state.showCounter;
    },
  },
});

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

export const { increment, decrement, increase, toggleCounter } = counterSlice.actions;
export default store;

 

오래된 방법이 사라져서 toolkit을 사용하는 것이 더 합리적이라고 생각이 든다.

그리고 이 부분에서 가장 중요한 것은 State를 직접적으로 변경해서는 안된다.

예를 들면, state.counter = state.counter +1 , 이 부분을 state.counter++ 이런 식으로

직접 변경이 가능한데, 보이기에는 오류가 없어보이나 직접적으로 변경했을때 state가 변형돼

큰 오류를 발생키는 위험이 있을 수 있기때문에 항상 복사해서 쓰는 걸 명심하자!

 

++ 그런 줄 알았으나. toolkit에서는 직접 바꿔서 사용해도 실질적으로 State는 바뀌지는 않는다.

이전의 counterReducer 같은 방식을 사용할때는 절대 직접 바꾸면 안됐었는데, toolkit에서는 내부 숨겨진 로직으로

본래의 값을 변경하지 못하게 설정되어 있다.

그러므로 toolkit Slice를 사용할때는 state.coounter++로 사용해도 상관없다.

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

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

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

export const { increment, decrement, increase, toggleCounter } = counterSlice.actions;
export default store;

'Frontend Study' 카테고리의 다른 글

Redux #4 Redux Thunk  (1) 2025.01.07
Redux #3 _ 다중 Slice  (0) 2025.01.06
Redux 기본 원리  (0) 2025.01.05
React _ Redux 왜 써야할까?  (1) 2025.01.05
React _ 미니프로젝트#3 마무리  (0) 2025.01.05