DEV Community

Jayant Khandelwal
Jayant Khandelwal

Posted on

The best Couple: useContext + useReducer !


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

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


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

Top comments (4)

aoloo profile image
Allan Oloo • Edited

const contextValue = useMemo(() => {
return { counterCount: count, counterDispatch: dispatch };
}, [count, dispatch]);

In your step 2 I would possible memoize the values your passing to your provider for perfomance optimization. The object will always be recreated when the app component renders, which would cause all the children utilizing the context to re-render.

mrezah1 profile image

thanks , wsa useFul👌🙏

jackent2b profile image
Jayant Khandelwal

Most Welcome!!

ramansain profile image
raman sain

great explanation