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 counter to counters! makeMultiReducer works with any reducer, big or small, even ones created using combineReducers.

NOTE: 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.

--

--

Founder, Jovian

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store