Welcome to part-6 of the series. We will learn about using redux with react with the latest hooks in this part.
This is a new pattern in react-redux, where instead of using the HOC, we can use the hooks provided by redux.
We will first use the useSelector hooks, which is equivalent to mapStateToProps(). Create a new file HooksEggContainer.js in the components folder.
Here, we have imported the useSelector hook from react-redux and using it to get the value stored in the reducer.
Now, we will include it in the App.js file.
Now, if we go back to localhost, we can see it.
Now, we will add the useDispatch hook, which is used to dispatch an action and is quite similar to mapDispatchToProps().
Here, we are first importing the useDispatch. After that we are calling it and storing in a variable dispatch. Next, from the button onClick we are calling it to call the action creator buyEgg().
Now, if we go back to localhost and click on the button it will decrease the egg count.
Next, we will look into the practical example of having multiple reducers. For this, we will follow the same steps which we did for Eggs.
Inside the redux folder, create a new folder chicken. Create three files chickenActions.js, chickenReducer.js and chickenTypes.js inside it. All the code will be exactly similar to the Egg part.
The content of chickenTypes.js is below.
The content of chickenActions.js is below.
We also need to make sure to export this action from our index.js file.
Next, we will write the code for chickenReducer.js file, which is again similar to it’s egg counterpart.
Next, we will make the redux store aware of this reducer. And now the concept of combine reducer will come into picture. For this create a file rootReducer.js inside the redux folder. In it add the code to use both reducers, with the help of combineReducers.
After that back in store.js use the rootReducer.
Now, to use all these create a new file HookChickenContainer.js inside the components folder. The content for it is exactly similar to it’s egg hook counterpart.
Now, also include it in the App.js file.
But, if we go to localhost now it will seems sort of broken.
This, is because we have divided the state with the use of combineReducer. So, now we have to use it by the name which we have given in the rootReducer.js file.
So, update state in HookChickenContainer.js file.
Similarly, update state in HookEggContainer.js file.
Also, update the state in the HOC based EggContainer.js file.
Now, if we move to localhost everything will work fine.
This completes part-6 of the series.
You can find code till here in this github repo.