DEV Community

loading...

The best Couple: useContext + useReducer !

jackent2b profile image Jayant Khandelwal ・2 min read

Disclaimer:

This is going to be one of the best post you have ever come across in search of useContext + useReducer hooks!

Why do we use useContext and usereducer together?

Reason: To share states between the components i.e. Global State
Management

In the previous posts, we have seen how to make use of useContext and useReducer hooks.

So, in this post, we will see how to make use of them together!

Alt Text

In this example, we are going to share the state of the counter between Component A , Component D and Component F!

Also, the Components hierarchy in our example is as follows:

1.)Component A
2.)Component B -> Component D
3.)Component C -> Component E -> Component F

Steps:

1.) Create React context in the main component

2.) Make reducer function in the main component

3.) Make use of the useReducer function.

4.) Send context value using Context Provider

5.) Consume Context Value using useContext hook.

6.) Transfer action from the components using dispatch

Okay so let's get started!

Step1: Create React Context and reducer() function:

Alt Text

Step2: In the functional component, call useReducer(reducer,initialState) hook :

Alt Text

Here, you can see that we have passed the state i.e. counter and dispatch method as the value in the Context Provider.

Step 3: Now, in order to access the global state in Component A, Component D, and Component F, we need to make use of the useContext Hook to consume the context value passed by the Context Provider.

(component A)
Alt Text

(component D)
Alt Text

(component F)
Alt Text

Step 4: In order to change the global state through Components A, D, and F, we have passed action (i.e. increment, decrement, or reset) through the dispatch function.

This is all you need to manage the global state using useReducer and useContext hook!

I hope it might have helped you!

Do share your thaughts!

*Happy Coding, Thank you! *

-Jayant Khandelwal

Discussion (0)

pic
Editor guide