리덕스 : 상태관리 라이브러리
리덕스 툴킷 : 리덕스를 편하게 사용할 수 있도록 도와줌.
리덕스 상태→ store 라는 저장공간의 트리에 저장됨.
상태 트리 변경 방법 : action을 보냄. 무슨 일을 할지 서술된 객체임.
reducer: action이 어떻게 변경할지 정해주는 것
Redux 툴킷을 사용하면 코드가 더 개선되고 유지 관리가 쉬워진다.
이 API는 Redux 로직을 작성하기 위한 표준 접근 방식이다.
초기 상태, 리듀서 함수의 객체, "슬라이스 이름"을 받아 리듀서 및 상태에 해당하는 액션 생성자와 액션 유형을 자동으로 생성하는 함수.
내부적으로 createAction, createReducer를 사용하므로
Immer를 사용하여 변경 불가한 업데이트를 작성할 수 있다.
function createSlice({
// A name, used in action types
name: string,
// The initial state for the reducer
initialState: any,
// An object of "case reducers". Key names will be used to generate actions.
reducers: Object<string, ReducerFunction | ReducerAndPrepareObject>
// A "builder callback" function used to add more reducers, or
// an additional object of "case reducers", where the keys should be other
// action types
extraReducers?:
| Object<string, ReducerFunction>
| ((builder: ActionReducerMapBuilder<State>) => void)
})
initialState
: 초기 상태 값
name
: 문자열 이름
reducers
: createReducer
되므로 reducers
는 주어진 상태를 안전하게 mutate
할 수 있습니다.
import { createSlice } from '@reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: 0,
reducers: {
increment: (state) => state + 1,
},
})
// Will handle the action type `'counter/increment'`