useContext Hook in React.js

Arjun Bharti
2 min readMay 26, 2021

--

Remember in the previous blog I talked about “Prop drilling” in React.js.
If you haven’t yet read it, please click here and read that blog post first.

The useContext hook in React.js makes it really easy to pass data throughout the application without manually passing the props in the component tree.
The context is initialized with createContext top-level API.

We have three things in Context API (i.e context, provider and consumer).
First of all, we will create a context and it will return the object having two values known as provider and consumer.

useContext example code

With the help of the provider, the given colorName will be available to all children and grandchildren in the code.
Then the consumer will help us to get the value of colorName from the context. Now, you can clearly see here that there’s no prop passed to transfer the data. The whole subtree in the code is able to use the Consumer to read out the value of colorName.

Remember there are three things in the Context API:

The context pair (React.createContext)
The two components that communicate with the context pair:
Provider and Consumer

The provider and consumer are bound together and they cannot be separated. If we have two different context in our code, let’s say contextA and contextB, then the Provider and Consumer of contextA would not be able to communicate with the Provider and Consumer of contextB.

The Providers accepts only one value irrespective of its type. It can be a string or number or anything. We can pass multiple values by creating an object with all the values and pass that object in the code.

Thanks for reading. Hope you learnt something new today!

--

--

Arjun Bharti
Arjun Bharti

Written by Arjun Bharti

Ex-Developer Student Clubs - LEAD, CS Student, Web/Mobile Apps Developer

No responses yet