Redux Toolkit은 Redux를 사용하는 개발자들을 위한 공식적인 Redux 라이브러리입니다. Redux Toolkit은 Redux 애플리케이션을 개발하고 관리하기 위해 사용되는 일련의 유틸리티 함수와 도구를 제공합니다. 이 라이브러리는 Redux 개발 경험을 개선하고 보다 간편하고 생산적인 방식으로 애플리케이션 상태를 관리할 수 있도록 도와줍니다.
-chatGPT
npx create-react-app my-app --template redux-typescript
npm install @reduxjs/toolkit react-redux
설치를 하고 npm으로 실행을 하면 counter 앱이 나온다.
기본적으로 index.tsx파일에서 Provider component에 store객체를 제공하고 있다.
src/features/counter/counterSlice.ts 파일에는 counter기능을 위한 reducer들이 정의되어있다.
export const counterSlice = createSlice({
name: 'counter',
initialState,
// The `reducers` field lets us define reducers and generate associated actions
reducers: {
increment: (state) => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload;
},
},
// The `extraReducers` field lets the slice handle actions defined elsewhere,
// including actions generated by createAsyncThunk or in other slices.
extraReducers: (builder) => {
builder
.addCase(incrementAsync.pending, (state) => {
state.status = 'loading';
})
.addCase(incrementAsync.fulfilled, (state, action) => {
state.status = 'idle';
state.value += action.payload;
})
.addCase(incrementAsync.rejected, (state) => {
state.status = 'failed';
});
},
});
slice의 이름, 초기 상태, 어떻게 변경되는지(reducer)를 정의한 slice이다.
createSlice()의 인자로 넘어가는 값은 object이며 reducer 프로퍼티의 value 또한 object로 구성되어 있다. 예제를 보면 increment, decrement에 대해서 어떻게 상태변경을 할 것인지에 대한 로직이 나와있고 이에 대해 주목할 점이 2가지가 있다.
하나는 각 type에 대해서 어떻게 action을 처리할 것인지에 대해 화살표 함수로 표현하고 있는데, 함수의 인자로 object를 받고 이는 이전에 지정했던 initialState 혹은 변경된 state를 가리킨다.
다른 하나는 각 action을 처리하는 함수에서 state의 value를 직접 건들고 있지만 redux는 immutable이므로 inner 라이브러리를 사용하기 때문에 실제로는 직접 상태를 변경하는 것이 아니다.
Redux Toolkit에서 "slice"는 Redux 애플리케이션에서 상태 및 관련 로직을 구성하는 단위입니다. Slice는 액션 생성자, 리듀서 및 선택자와 같은 Redux 기능을 하나의 모듈로 그룹화하는 방법을 제공합니다. Slice를 사용하면 코드를 구조화하고 중복을 피하며 애플리케이션의 상태 관리를 쉽게할 수 있습니다.
Slice는 createSlice 함수를 사용하여 생성됩니다. createSlice 함수는 Slice를 생성하는 데 사용되며, 액션 타입, 액션 생성자 및 관련 리듀서를 자동으로 생성합니다. Slice를 생성할 때는 초기 상태(initial state)와 리듀서에 대한 리듀서 함수를 정의해야 합니다.
-chatGPT
위와 같이 toolkit을 사용하지 않을 때에는, 여러 개의 reducer 함수를 만들고 해당 reducer함수를 rootReducer에 등록을 한 다음에 createStore()의 인자에 rootReducer를 등록하는 방식이었다.
하지만 slice를 이용함으로써 훨씬 더 간편하게 reducer를 등록하고 관리할 수 있다.
import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';
export const store = configureStore({
reducer: {
counter: counterReducer,
},
});
store 객체를 생성할 때는 기존에 createStore()가 아닌 configureStore()f를 이용한다.
인자로는 object 하나를 넘기며, 해당 object의 property에 reducer가 있고 reducer의 value를 object로 하며 해당 object 안에 counter라는 이름으로 counterReducer(slice)를 등록한다.