Reducing Reducers [NGRX]: How to extend third party reducers
Sometimes, we need to extend third party library reducers and add additive features on top of it. This can be done easily with the help of a simple trick.
NGRX is a reactive implementation of Redux architecture where reducers act as reactive setters to add data to our application’s Observable Store on listening to Actions.
Reducing Reducers
Alliteration Alert! (see what I did there)
Since we need to extend an existing reducer by adding additive features to it, we need to essentially concatenate
the reducers. Since reducers are pure functions which receive the state
and action
and return the new state, we can essentially reduce reducers and concatenate them together 🎉
We can write a function to help us do this. We have also added another helper to concatenate reducerFactories
which is required for AOT builds with previous versions of angular (with ViewEngine)
Explanation:
- We have written a function called
concatReducers
which takes an array (parameter list) ofActionReducers
- We use the
Array.prototype.reduce
function with the initial state as the starting seed for the reduce method - The reduce method iterates over the array of reducers and calls each reducer with the accumulated state and the action. This is the secret of the concatenation of the reducers, as the previous reducer’s result becomes the input for the next reducer call.
Extending Third Party Reducers
Here’s a trivial example where we’re extending the @ngrx/router-store
reducer and concatenating a custom reducer with it. This will allow us to listen to additional actions and extend the original reducer provided by the package. You can use this trick for extending any existing reducers
Summary
In some rare cases, we need to extend NGRX reducers provided by third party libraries. In these cases, we can take advantage of functional programming to concatenate our reducers by reducing an array of reducers. If you want to learn more about NGRX, check this book out
Thank you for reading and I hope this helps you as it helped me.
I would love to know in the comments below if this was useful!