React Redux tutorials for beginners-3

Image for post
Image for post
Coding

Welcome to part-3 of the series. You can find part-2 here.We will learn about the concept of multiple reducers first.

We will continue with our example project. Suppose our Egg shop now wants to sell Chicken also, we will have to go through the whole setup again to use it.

Here, we are first adding the constant and after that our action creator buyChicken(). Next, our initial state also contains the numOfChickens variable. And then we will add it in the reducer.

Image for post
Image for post
index.js

Now, we just need to dispatch the new action creator buyChicken(). After that open the terminal and run node index to see the result. We can see both the initial state and the updated state given by our code.

Image for post
Image for post
action creator

Now, this approach to use one reducer is fine for small project, but in large projects we generally follow a different approach of Combine reducers. We will see that next.

For the combine reducer approach, we split everything. First, we will split the initialState as initialEggState and initialChickenState.

Image for post
Image for post
index.js

Next, we will also divide the reducer in two separate reducer — one for egg and the other for chicken.

Image for post
Image for post
Separate reducers

Now, to combine the reducers, we use a method from redux called combineReducers. So, we will import it at the top.

Image for post
Image for post
combineReducers

Now, we will use the combineReducers to add an egg and chicken key in an object. The value will be the eggReducer and chickenReducer.

Then we are using this rootReducer, to create our store. Now, when we move to our terminal and run node index, we will see our code in action. But one thing to notice is that the format is changed.

Image for post
Image for post
combineReducers

This completes part-3 of the series. You can find part-4 here.

You can find code till here in this github repo.

Written by

UI Lead- ReactJS, JavaScript and everything in-between.

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