どうも、ウマシバ(@UMASHIBA)といいます。redux-toolkitを触ってみたので何が便利になったのかという点を備忘録のために雑にまとめたいと思います。
redux-toolkitとは
最近できたreduxを簡単に書くためのライブラリです。
Reduxの公式ページでも紹介されているライブラリです。
- configureStore
- createAction
- createReducer
- createSlice
といったような簡単にreduxを書くための関数が用意されています。
詳しくはこちら
configureStore
// Before:
const store = createStore(counter)
// After:
const store = configureStore({
reducer: counter
})
reduxのcreateStoreとほとんど書き方は変わりません。
ただRedux DevTools Extensionみたいな便利なミドルウェアをデフォルトでいれといてくれます。このミドルウェアをデフォルトで入れておいてくれる機能は便利だと思います。
createAction
// Original approach: write the action type and action creator by hand
const INCREMENT = 'INCREMENT'
function incrementOriginal() {
return { type: INCREMENT }
}
console.log(incrementOriginal())
// {type: "INCREMENT"}
// Or, use `createAction` to generate the action creator:
const incrementNew = createAction('INCREMENT')
console.log(incrementNew())
// {type: "INCREMENT"}
typeとactionの定義が同時にできるので便利
これで大量のactionとtypeを別々に書いてエクスポートしていたのが一つで済むようになりそうです。
createReducer
const increment = createAction('INCREMENT')
const decrement = createAction('DECREMENT')
//BEFORE
function counter(state = 0, action) {
switch (action.type) {
case increment.type:
return state + 1
case decrement.type:
return state - 1
default:
return state
}
}
//AFTER
const counter = createReducer(0, {
[increment.type]: state => state + 1,
[decrement.type]: state => state - 1
})
上のコードを見てみると相当コードを書く量が減っています。
書くコード量が多くなってしまうReduxにおいてこの利点は相当大きいと思います。
createSlice
const counterSlice = createSlice({
name: 'counter',
initialState: 0,
reducers: {
increment: state => state + 1,
decrement: state => state - 1
}
})
const store = configureStore({
reducer: counterSlice.reducer
})
document.getElementById('increment').addEventListener('click', () => {
store.dispatch(counterSlice.actions.increment())
})
createSliceはaction, type, reducer全てを定義してくれます。
上記でやったcreateAction, createReducerを合わせたような関数です。
すごく書くコードの量が減る。便利!
更にすごいのはこのcreateSlice関数を使った場合返す値がイミュータブルであるか気にする必要がありません。
createSliceで勝手にimmutableにしてくれます。つまり元のstate
に対してArray.push
メソッドとかが使えます。
まとめ
redux-toolkitはコード量を少なくReduxを書くためのライブラリ
という風にまとめられると思います。
Reduxの公式ページにも紹介されておりGitHubのStarも2020/5/16時点で3000以上あり廃れにくそう。