DEV Community

Cover image for Redux: Combining Reducers
Adriana DiPietro
Adriana DiPietro

Posted on

Redux: Combining Reducers

Today I will be discussing why and how to combine reducers in a Redux managed application.

Questions for Understanding

  1. What is Redux?
  2. What is a reducer?
  3. What is the Redux store?
  4. What is a library?
  5. What is state?
  6. How is state in Redux different than state in React?

💬Let's keep these questions in mind during our discussion today!💬

Combining Reducers

Here is an example of using "combineReducers" in my latest project:

// reducers/index.js

import { combineReducers } from "redux"
import userReducer from "./userReducer"
import bookmarkReducer from "./bookmarkReducer"
import categoryReducer from "./categoryReducer"

const rootReducer = combineReducers({
  users: userReducer,
  bookmarks: bookmarkReducer,
  categories: categoryReducer
})

export default rootReducer
Enter fullscreen mode Exit fullscreen mode

"combineReducers" is an utility function given to us from the Redux library. Thus, I import it at the top of my file. "Utility" meaning it provides our application some behavior and does a job for us. This job, its purpose, (as the name gives away) is to store all of an application's reducers in a single reducer. Combination. In the case of my application, it stores all of my reducers in a constant I declared called "rootReducer".

Within my rootReducer, I call on combineReducers() to accept some objects and set each object to be a key in my root state object of my application.

I import all three (3) of my reducers: userReducer, bookmarkReducer, and categoryReducer from their delegated files. Then within my combineReducers() utility function I assign each of my reducers to a key. The key name can be anything you choose, but by standard it is a good idea to reflect the name of the reducer.

Hence:

 users: userReducer
Enter fullscreen mode Exit fullscreen mode

combineReducers, in effect, splits the root state of an application and delegates different parts of the state to a reducer.

In our ReduxDevTools console, we can see this effect take place:

Screen Shot 2021-09-01 at 12.54.37 PM

We can see all three (3) key-value pairs created by combineReducers(). Once one is expanded, we can see the state returned by that individual, specific reducer:

Screen Shot 2021-09-01 at 12.55.18 PM

💬💬💬

This is a simplified explanation of combineReducers(). Despite its nature, I find it helpful to look at the basics + key concepts of something so complex like Redux. Whether you are a beginner developer or been doing this for years, I hope this has found you well.

💬Comment below to continue the discussion + feel free to ask any questions!💬

Top comments (2)

Collapse
 
veera_zaro profile image
Veera

Nice article Adriana... Looking forward to more like this!

Collapse
 
am20dipi profile image
Adriana DiPietro

Thank you Veera for the comment! Definitely more to come :)