Skip to content

Redux Toolkit

Created: 2021-06-27 15:43:21 -0700 Modified: 2021-08-08 20:34:29 -0700

Redux, on its own, has a lot of boilerplate. Redux Toolkit adds an opinionated way of managing Redux.

I first used it in Homepagerizer, which is open-source, so I’ll include references to that codebase in these notes.

Use a thunk:

function multipleDispatches() {
return function (dispatch) { // the second argument would be getState
dispatch(someAction());
dispatch(someOtherAction());
};
}
// later…
dispatch(multipleDispatches())

For asynchronous calls, use createAsyncThunk.

If you need the result of a Redux hook, pass it as an argument to multipleDispatches.

Having multiple reducers respond to the same action

Section titled Having multiple reducers respond to the same action
  1. Put the shared action in a separate file, e.g. here.
  2. Use extraReducers (e.g. here) to add a case for handling that action. Remember that “state” will only contain that slice’s state, not all state, hence why you even need multiple reducers in the first place.

Allowing multiple arguments from an action creator

Section titled Allowing multiple arguments from an action creator

By default, an action’s payload is only a single property.

  • When in createSlice, change your reducer from a function into an object with two keys: reducer and prepare. See this code.
  • When in createAction, the second argument is the prepare function. See this code.

Use currying:

export const selectEditingItem = (state) => {
return {
rowNum: state[reducerName].rowNum,
itemNum: state[reducerName].itemNum,
};
};