A class-based approach to writing reducers in Redux/NgRx
Everyone involved in front-end development agrees that Redux is a good thing, or at least most do. Many though aren’t in love with the amount of boilerplate needed to write even the simpler reducers. Others just don’t like switch statements and that’s fine.
What I propose is a simple class-based approach that lets us write reducers without any switch statement, inferring the actions using reflection. Most React/Redux devs will definitely dislike this, while Angular/Ngrx users may instead see some familiarity with the following code. Either way, it’s just another way of doing it, certainly not a better one.
To show this I created a simple utility called typed-reducer
which I published on Github
First of all we define our actions as classes. Types wouldn’t be needed but some frameworks may complain as the interface would not adhere to the standard.
Now let’s write our reducer as a class and build a commonly known reducer using `typed-reducer`.
We import a decorator called Action
and a function called createReducer
. We apply the decorator `Action` to the methods we want to use to reduce the state. Then, we call the function `createReducer` and we pass to it the reducer class and the initial state.
Let’s see some code:
As you can see, it is just enough to add the decorator @Action
and the method is automatically picked up when an action is dispatched by a component. By using classes to define our action types, we achieve two things: we strong-type our actions and we don’t need to use any branches to tell our code what nee
Because of this class-based approach, I think this plays particularly nicely with NgRx (which I’ll be using in the next example), rather than Redux. It doesn’t have any particular dependency so it could be used with any Redux variant.
Let’s now dispatch an action using the classes we created using @ngrx/Store.
This utility is obviously not ready for production use and wouldn’t recommend you to use on it in case you liked it, but it would be great to hear your thoughts about it!