Reusing Reducer Logic in Redux
You’re using Redux to maintain the state of a counter in your web application, and it’s great! Well, what if you need two counters, or three, or ten, or a variable number?
Here’s a simple higher order reducer (aka utility function) that can help you reuse the
counter reducer for managing the state of multiple counters:
To use it, simply wrap a reducer with
makeMultiReducer, and dispatch actions with a
key property. To access the state, create a selector using
makeMultiGetter. Here’s an example:
Two extra lines of code is all it takes go from
makeMultiReducer works with any reducer, big or small, even ones created using
makeMultiReducer is part of an open-source library called
dextrous, which contains several other utility functions I use for reducing boilerplate and reusing reducer logic in Redux.