React Hooks tutorials for beginners-8
Welcome to part-8 of the series. You can find part-7 here. We will learn more about useReducer hook in this part.
In the previous part, we had created a different state variable to do basically the same functionality in in second counter. There is an easier alternative to do it and we will see it first.
Create a new file CounterThree.js in the components folder. The content of it is similar to CounterOne.js, except the one which are highlighted below.
Here, we are creating a new count2 and dispatch2 with the same reducer logic. After that we are using them to create three new buttons with same logic.
Now, include this in App.js file.
Now, in localhost both will work and independent of each other.
useReducer with useContext
Till now we had used useReducer to do local state management. But the real power of it comes with global state management like redux. We do it with combining useContext with useReducer.
To understand this with an example, we will again create a deep level of nesting.
First from App.js import three components GrandParent1, GrandParent2 and GrandParent3.
Next, let’s create GrandParent1.js file with below content.
Next, we will create GrandParent2.js file with Parent1 component.
Next, we will create GrandParent3.js file with Parent2 component.
Now, we will create the Parent1.js file with below content.
Next, we will create Parent2.js file with the Child1 component.
Lastly we will create the Child1.js file with below content.
Now, our goal is to maintain a count state in App.js and modify the state from different Components.
We will update our App.js to have the reducer logic for a simple count, which we had learned earlier. After that we are wrapping the jsx with CountContext and passing the count and dispatch as an object.
Now, it’s time to use it in components which are nested at different level. We will first update GrandParent1.js file. Here, we are just importing the CountContext and then using both the countState and the countDispatch. The button trigger from here, will run the reducer logic in App.js file.
Next, we will update the same logic in Parent1.js file.
We will also update the same in Child1.js file.
Now, we have a global state which can be updated by any component and the state variable can also be accessed by any component. This is a complete implementation of Redux, but in a much simpler way,
This completes part-8 of the series. You can find part-9 here.
You can find the code for the same in this github repo.