Writing Redux code can quickly become boilerplately and difficult to understand. This applies especially on larger projects or when you’re needing to update an incredibly nested property.
We can make use of two libraries to very easily adjust your approach while making your code much cleaner and far more readable.
Redux-actions allows us to rapidly produce generic action creators (as well as create action creators that manipulate the data before returning the action object) while reduxjs/toolkit allows for us to structure our reducers in a different way plus make us of immer. Immer is a library that allows us to write code in a mutable fashion by making use of a proxy state, however, the updates to our store are actually performed immutably.
This describes the flow of immer. You’re provided with a draft (or proxy) state that represents the current one. You can then make changes to that draft state. After you’re done making changes, that draft state will be persisted to the store as the next state.
Let’s look at our actions.js file from the ShopDrop application we created in the previous blog.
Our actions currently look like this:
If we import the redux-actions library into our project using npm i redux-actions, we’ll then be able to import the createActions function. Using that function, we can rapidly produce action creators that would be identical to the example you see above.
All we need to provide this method is the type of the action (like we normally would) and it’ll implicitly build a function that would take data and return that as a payload. The result of the above could would provide is with an actionCreators object that if we were to log, would look like this:
A function is generated in the form of camel case based on what string literal type we provided to the method.
Note: Check out the API to see how you could perform data manipulation prior to creating the action object.
Our previous reducer.js would have looked like this:
After importing the new library using npm i reduxjs/toolkit, we could make use of the createReducer function. This function allows us to build a reducer without having to have a switch cache (and thusly mitigating the need for string constants for action types everywhere). The biggest bonus is that this library is a wrapper for immer which means it allows us to make changes mutably.
Our new reducer could look something like this:
You can see how much easier this makes updating nested properties and also how much easier it is to read. We could go from this:
As usual, a CodeSandBox for this project is available here if you want to mess around and dive into the code.