React Redux tutorials for beginners-3

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

Multiple Reducers

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.

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.

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.

Combine reducers

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

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

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

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.

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

You can find code till here in this github repo.

--

--

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
Nabendu Biswas

Nabendu Biswas

589 Followers

Founder TWD, JavaScript & ReactJS Trainer, Youtuber, Blogger