DEV Community

Abiodun Olowode
Abiodun Olowode

Posted on • Edited on

THE COOLEST THING ABOUT THE REDUX STORE IN REACT

Yeah, React is cool and Redux is cool too but you know what is the coolest thing about these two when they interact? CombineReducers!!!.
CombineReducers makes it possible to refer to the properties of the store state by the names of the individual reducers that were combined; that way, you are never in doubt about what property you want to access, you just need to name your reducers accordingly. Pretty Cool!!, ain't it?

Let us start by creating the several reducers we intend to have, this is determined by the distinct properties we expect our state to possess. For instance, if you want your state which is stored in your redux store to have a books property, which when called will produce a list of books, you create a reducer called books.

Alt Text

There's something fishy about the code above though; Have you figured it out? Yes, you are right!!! Random numbers!!! Id's are meant to be unique, random numbers could end up being the same and hence, generate an error. Do take note!

Back to discussing our state, if we want our state to have another property called filter, that returns a boolean value, we create a reducer called filter which returns a boolean.

Alt Text

It is worthy of note that in this article, I have not added action types to the individual reducers but I have gone ahead to return state as default; that is because you are free to add whatever action types are required by your app, it is not the focus of this article.
All these reducers can be in their .js files and stored in the reducers folder. The most important thing is creating the rootReducer which will be connected to the store and combining the above-mentioned reducers in it. How do we do this? We import combineReducers from redux and apply its magic.

Alt Text

Having combined the reducers in our rootReducer, we can now create our store and link it to the rootReducer.

Alt Text

As the name implies, the Provider makes the store available to any children or grandchildren nested inside it. I would tell us how we can access this store in a later article, as a result, you can ignore lines 11 through 16 of the code above.

Well, as simple as that, everything is set and if we run a console.log of store.getState().books, we would get the list of books and if we run store.getState().filter, we would get the boolean value of true.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.