DEV Community

Jayant Khandelwal
Jayant Khandelwal

Posted on • Edited on

4

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up