Welcome to part-6 of the series. You can find part-5 here. We will learn about useContext hook in this part.
We have learned about context in the React tutorial series. You can learn more about it here.
To quickly recap — 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 Component is required by Component C. Now, it have to pass through the Component A and B also. Although they don’t need it.
We will first see the problem with the traditional Context API. So, go ahead and create a new react project with the below command.
npx create-react-app context-hook
Next, create a folder components inside the src folder. Inside it create three files Child.js, Parent.js and GrandParent.js
Put the below content in Child.js file.
Now, call the Child component from Parent.js file.
Now, call the Parent component from GrandParent.js file.
And finally call the GrandParent component from App.js file.
Now, we want to pass props from App to Child directly and we will create context for the same.
We need to create the UserContext with React.createContext(). After that we have to wrap the GrandParent component with Provider. We are then pass the value, which can be accessed from any other component.
We will then first import the UserContext in Child.js file. Next, in the jsx we need to use the render props pattern, to get hold of the value passed by the context.
Here, we are wrapping the whole jsx in Consumer and then using the value with user.
Now, in localhost we can see the value Nabendu been shown.
The context feature is great but the code gets complicated quickly, once we have multiple context.
Back to App.js, we will pass another value. So, we will create a new ChannelContext and wrap GrandParent with it.
Back to Child.js, we will consume the value. For this in our return statement for user, we are adding the ChannelContext Consumer.
As, we can see from above the code get’s complicated pretty soon and if we need to pass another value, the nesting will only increase.
It shows ok on localhost.
The useContext hook is used to consume the value in a much simpler way. The Provider will still remain the same.
For useContext, let’s consume the value in Parent component. Here, we are first importing the userContext and ChannelContext. Then, we are getting the value with simple one liner like
const user = useContext(UserContext).
After that we can use the variable with the usual jsx syntax.
So, our code have become very simple with no nesting thing and it will also look perfect in the browser.