• A Few Notes on Composition of Reducers by Ast

    Managing the state of an application with libraries like `redux` is awesome. It provides a really easy way to write simple and testable code for state transitions. You only need to decide on a structure of the desired state and write a corresponding pure function.

    There is no doubt that a reducer could look super simple in the cases like the following one:

     

    Our main task as developers is to keep all reducers as simple as possible. Simple reducer is easily understandable and it's not a big deal to write a couple of helpful tests for it. But the state grows bigger and becomes more and more complex as we add more cool features to our apps. We need a technique to hide this complexity somewhere.

    Every reducer is just a common pure function. No magic at all. Therefore it's possible to write such a reducer function which will take a set of other reducers on its input to produce their results in a combination of some sort. Let's look at a few examples:

    Combine a set of reducers into a map of properties

    Let's assume that our app needs two different counters at the same time. It would be great to code something like that (with magic `combineReducers` function):

     

    And it's exactly what is possible with the standard `combineReducers` function from `redux` library. But be aware that as we use the same `counter` reducer for counter1 and counter2, they react the same way and counter's values will be the same too.

    Combine a set of reducers into an indexed storage

    Let's imagine that we want a couple of such state structures. We must add an `id` parameter into the action to be able to determine which one of the states we want to change.

     

    Let the power of pure functions be with you.

comments powered by Disqus