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 image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay