DEV Community

Jayant Khandelwal
Jayant Khandelwal

Posted on • Updated on

Making use of useContext Hook!

Welcome back devs!

We have talked about using ContextAPI, how to create context, how to Provide context value, and how to Consume context value in the last post of the series.

In this post, we are going to see how to make use of useContext Hook.

Description:

useContext accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest above the calling component in the tree.

When the nearest above the component updates, this Hook will trigger a rerender with the latest context value passed to that MyContext provider

Following are the changes you need to make to our previous code in our earlier code in order to use useContext hook:

Now,

useContext

vs

Before,

without useContext

Only this code you have to change, the rest all remains the same as it is.

Note: useContext(MyContext) only lets you read the context and subscribe to its changes. You still need a above in the tree to provide the value for this context.

Stay tuned for the upcoming posts of the Series!!

I hope it might help you, Feel free to leave a comment if you have any doubt!

Feedbacks are always welcome!

Happy Coding!

-Jayant Khandelwal

Top comments (0)