Passing state between reducers in Redux

Ryan Johnson
ITNEXT
Published in
2 min readFeb 27, 2018

--

Want to learn React? Check out my new course React for Beginners: Build and app, and learn the fundamentals.

Have you ever had a slice of state from one reducer that you needed access to in another reducer? If you’re using Redux’s combineReducers out of the box then you may be stuck, or you could use reduce-reducers, but that may be overkill for your needs.

Instead why not write your own combine reducers?

It’s easy to forget that reducer’s are just a functions with the following format (previousState, action) => newState, and there’s no reason you can’t write your own version of combineReducers to handle this scenario. The following is a pattern I use to access state from different slices in my reducer.

For example if we were building an app that deals with localization we might have the following state shape:

In the above state languages is an array of languages the app supports, while translations is an object where each key’s value is an array with a translation for each supported language. If we were using combineReducers to assemble this state it would look something like this…

The above works fine, but what happens if we need access to data from languages from the translations reducer? If you’re using combineReducers you will only have access to your reducer’s state. Instead you can use the following pattern to create a custom reducer function that combines your reducers, and passes the required data across reducers.

Although this pattern works well enough, I would not abuse it. If you find you’re having to frequently pass state across multiple reducers it may be a sign that your state shape needs work. Either way remember reducers are just functions — don’t be afraid to experiment!

For more React, Redux, and JavaScript reading follow me on Medium or Twitter.

--

--

fullstack web developer • JavaScript • React.js • AngularJS • Node.js