Redux Toolkit
Created: 2021-06-27 15:43:21 -0700 Modified: 2021-08-08 20:34:29 -0700
Overview (reference)
Section titled Overview (reference)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.
Dispatch multiple actions
Section titled Dispatch multiple actionsUse a thunk:
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- Put the shared action in a separate file, e.g. here.
- 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 creatorBy 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.
useSelector with arguments (reference)
Section titled useSelector with arguments (reference)Use currying: