DEV Community

Cover image for Context ApI + useContext Hook (The deadly Beast)!!
Jayant Khandelwal
Jayant Khandelwal

Posted on • Updated on

Context ApI + useContext Hook (The deadly Beast)!!

Fun Fact:
Context API to State management in React, is Hammer to Hulk!

Don't you agree?
Check it out yourself :

"Context provides a way to pass data through the component tree without having to pass props down manually at every level."

Tree

Consider a Scenairo:

In the above Tree, if we need to access the username in Component A, Component D, and Component F then these can be the following ways:

Method 1.)
Pass it down through all the components as props i.e (B -> D) and (C -> E -> F). The Problem with this method is that we need to unnecessarily pass props through Component B, Component C, and Component E as they are the Parent Component of Component D and F. It decreases the efficiency of our software.

Method 2.) Use Context API

We will make use of Method 2:

Steps to Create Context

1.) Create the context
2.) Provide the context value
3.) Consume the context value

Let us consider only the case from (C -> E -> F).

Step 1:) Create the Context:

Create Context

In the first Step, we have made a context using React.createContext().

Step 2.) Provide the context value:

Provider

Now, we have used the Context Provider to pass the value to the components.

Note: value passed in Provider will be passed to all the components (and their Child Components) present inside the Provider Tag. In our case, the value will be passed to Component C and its child Components (i.e Component E and Component F).

Step 3.) Consume the context value:

Consume Context

Now we need to Consume the context value which we have passed down to Component C and its child Components. We will consume it in Component F.

In the return statement, place a Consumer tag and enclose the JSX function in it having the context value as arguments (username as an argument in our case).

Output:

Alt Text

This is how you can make use of Context API.

It can be noted that there is a little bit of hassle in order to consume context value

In order to make consumption of context value an easy task, we will make use of the useContext hook in the upcoming post!

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)