-
Notifications
You must be signed in to change notification settings - Fork 5
Redux toolkit
jch422 edited this page Dec 19, 2020
·
5 revisions
- Redux Toolkit은 Redux의 공식 개발 도구이다
- Redux 로직 작성을 위해 Redux 제작자들이 공식적으로 추천하는 방법
- 기존의 Redux를 사용하면서 액션 및 리듀서를 관리하기 위한 코드의 양이 늘어나는 문제를 해결가능!!
- 기존에는 리덕스 모듈하나를 만들려면 action type을 정의하고, action creator를 만들고 reducer까지 만들어야 했다
- 이 모든 작업이 createSlice 를 사용하면 한 번에 가능하다
- slice를 활용할 때 각각의 액션 타입은 자동으로 (name)/(reducers의 method명)으로 선언된다
-
Redux Devtools 기본 지원
-
immer 기본 지원 - immutable 하게 상태를 다뤄야 하는데 createReducer 안에서 push 하게 되면 자동적으로 immer 씀. immer 쓰게 되면 자동으로 immutable하게 상태 업뎃하게 됨.
-
thunk 기본 지원
-
Ducks pattern 기본 지원 (slice라는 이름으로 지원)
const todosSlice = createSlice({
name: 'todos',
initialState: [],
reducers: {
addTodo(state, action) {
const { id, text } = action.payload
state.push({ id, text, completed: false })
},
},
})name 으로 action이 생성될 때 prefix를 자동으로 붙여준다
prefix/action_name 대신 name 기반으로 dispatch 할 수 있도록 해준다.
//기존
dispatch({ type: 'todo/ADD', id: 1, text: 'contents'})
// slice
dispatch(todos.addTodo({ id: 1, text: 'contents' }))- configureStore 는 middleware 추가 하는 귀찮은 작업 한번해 해결
//기존
import { createStore } from "redux";
const reducer = (state, action) => { ... }
const store = createStore(reducer);
// toolkit
const store = configureStore({
reducer: rootReducer,
middleware: [ logger],
})- redux-action 지원
- createAction + createReducer
- create reducer은 handleAction(initial state + reducer) 이다
- createAction + createReducer
// 기존
function counterReducer(state = 0, action) {
switch (action.type) {
case 'increment':
return state + action.payload
case 'decrement':
return state - action.payload
default:
return state
}
}
// toolkit
import { createAction, createReducer } from 'redux-toolkit'
const increment = createAction('INCREMENT')
const decrement = createAction('DECREMENT')
const counter = createReducer(0, {
[increment.type]: state => state + 1,
[decrement.type]: state => state - 1,
})- createSelector = memoization + reselect
reselect 패키지는 원본 데이터를 다양한 형태로 가공해서 사용할 수 있도록 도와준다.
import { createSelector } from 'redux-toolkit'
const selectVisibleTodos = createSelector(
[selectTodos, selectFilter],
(todos, filter) => {
switch (filter) {
case VisibilityFilters.SHOW_ALL:
return todos
case VisibilityFilters.SHOW_COMPLETED:
return todos.filter(t => t.completed)
case VisibilityFilters.SHOW_ACTIVE:
return todos.filter(t => !t.completed)
default:
throw new Error('Unknown filter: ' + filter)
}
}
)📌 참고 자료