ReactJS Tutorial for Beginners -17

Welcome to part-17 of the series. You can find part-16 here. We will learn about Context in this part.

Context

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

We have a problem, when we need a prop some level deep from the parent. We need to pass the prop through all the nested component.

In the below example the Username prop of the App Componet is required by Component C. Now, it have to pass through the Component A and B also. Although they don’t need it.

Now, we will understand this with an example. Create a file Child.js inside components folder and put simple text in it as below.

Next, create a file Parent.js inside components folder and call the Child component from it, as below.

Then create a file GrandParent.js inside components folder and call the Parent component from it, as below.

Now, render it from the App.js file.

We have to first setup the context. For this create an userContext.js file inside components folder.

We create the context object with React.createContext(). It comes with a Provider and a Consumer React component. So, we will assign them to a variable and export them.

We need to use the Provider in a place, where all it’s Child component get’s it. A very good place is the App component, which is the beginning of all the Components in React.

So, in our App.js we will wrap the GrandParent component with UserProvider and pass the prop value to it. Now, it is available to all component ie GrandParent, Parent and Child.

We want to use the username in the Child component, so we have to use UserConsumer to wrap our jsx. It contains an arrow function, where you get access to the prop from the UserProvider. Note, that we can use any name here and we are using username.

There is another way to Consume the value in any component. For that we have to first export the UserContext from userContext.js file.

Now, we will use it in Parent component. Here, we use it with static contextType = UserContext

And it is equal simple to use it within the jsx with this.context

This way is very easy, but have a limitation that we cannot use with multiple nested Consumers.

This completes part-17 of the series. You can find part-18 here.

You can also find the code for the same in github repo, here.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nabendu Biswas

Nabendu Biswas

589 Followers

Founder TWD, JavaScript & ReactJS Trainer, Youtuber, Blogger