Today I will be discussing why and how to combine reducers in a Redux managed application.
Questions for Understanding
- What is Redux?
- What is a reducer?
- What is the Redux store?
- What is a library?
- What is state?
- 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
"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
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:
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:
💬💬💬
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)
Nice article Adriana... Looking forward to more like this!
Thank you Veera for the comment! Definitely more to come :)