Learn the useContext Hook in React
If you are a React developer, and haven’t learned about React hooks yet, it is the perfect time to start learning now. In this post, we are specifically going to learn about the useContext Hook. In the previous posts, we have covered some other hooks. Make sure to read them before you get started with this post.
Learn useReducer Hook in React
Note: If you are new to React, I would recommend learning Hooks first, and then learn older way of doing things if necessary.
‘Hooks are functions that let you “hook into” React state and lifecycle features from function component. They do not work within a class. They let you use React without a class.’ — React Official Blog post.
Alright! Let’s dive into useContext Hook.
What is Context in React?
If you are already a React developer you probably know what context is. In React everything is a component, and props as passed from the parent to the child component. This is the general principle of React’s component based single directional flow of data approach. But as your application grows, this may become cumbersome and not be ideal for certain global properties that a large number of components may require. For example, if you have user information that you want to display across multiple components, passing props through several components may not be ideal.
This is solved either by using external libraries like Redux which takes the entire state of the application and stores it in the Redux store or we can use React Context. Context provides a way to share values like these between components without having to explicitly pass props through the entire component tree.
To learn more about the concept of React Context with examples you can read the official blog post from React here:
https://reactjs.org/docs/context.html
What is useContext Hook?
The React Context API was introduced to overcome the problem of passing props down the tree of components. The state of the application can be stored globally, and shared across multiple components. Now with the addition of hooks to the React architecture, we get a new hook called useContext.
The useContext hook, just like all the other hooks we have seen before, is easier to write and works with React’s functional components. Previously, we could use the Context API only within class components. But with this hook, we can literally use context, within functional components with ease. It is also much easier to read and write.
Alright, let’s look into an example to understand this better.
Create Store
First step is to import the useContext hook.
import React, { useContext } from "react";
I am going to save the state in const blogInfo as shown below. This is the simple store for our example which holds the data.
const blogInfo = {
React: {
post: "Learn useContext Hooks",
author: "Adhithi Ravichandran"
},
GraphQL: {
post: "Learn GraphQL Mutations",
author: "Adhithi Ravichandran"
}
};
This data is our store, and you can create as many stores as you would like for chunks of data within your application.
Create Context
Now we can create context by passing in the blogInfo
const blogInfoContext = React.createContext(blogInfo);
We have now created the blogInfoContext and the next step would be to provide this context, so that the components can use it without having to receive props.
Provide Context to Components
Depending on what components may need the context, we can provide the context to components by using the Context.Provider. React does not care where in the component tree, the component exist. The idea is that, any component within the tree can get the context. In our example, I have created a parent component, and wrapped the Provider with the context value, for two other child components, BlogDetailComponent and MyOtherBlogInfoComponent.
function ParentComponent() {
return (
<blogInfoContext.Provider value={blogInfo}>
<h2>Use Context Example Component</h2>
<BlogDetailComponent />
<MyOtherBlogInfoComponent />
</blogInfoContext.Provider>
);
}
In our example, I have created a parent component, and wrapped the Provider with the context value, for two other child components, BlogDetailComponent and MyOtherBlogInfoComponent.
Enter useContext Hook
Up until the previous step, we didn’t use the hook. Once the context is provided to the components, we can use the hook within our functional component. The syntax for useContext is as follows:
const value = useContext(MyContext);
If you have previously used the React context, without hooks, you maybe familiar with Consumer. The useContext(MyContext), is similar to <MyContext.Consumer> in class components.
Never use useContext(MyContext.Provider) or useContext(MyContext.Consumer). The useContext hook only takes the context object itself as a parameter.
Component 1
Here we are going to use the hook useContext within our functional component. In our first component, I am using the blogInfoContext to display information related to React blog post.
function BlogDetailComponent() {
const blogDetails = useContext(blogInfoContext); return (
<div>
<h3>React Blog Details</h3>
<p>Topic: {blogDetails.React.post}</p>
<p>Author: {blogDetails.React.author}</p>
</div>
);
}
Note: The component that uses useContext will always re-render when the context value given to it changes. This means, we don’t need to do anything additional to keep track of the state change, as long as the context is available within the component.
Component 2
In our second component, I am using the blogInfoContext to display information related to GraphQL blog post.
function MyOtherBlogInfoComponent()
const blogDetails = useContext(blogInfoContext); return (
<div>
<h3>GraphQL Blog Details</h3>
<p>Topic: {blogDetails.GraphQL.post}</p>
<p>Author: {blogDetails.GraphQL.author}</p>
</div>
);
}
Putting it all together
Here is the code-sandbox, that shows all of this put together and working. Take a look at the ComponentUseContext.js file, to understand how the example works.
Conclusion
This post was originally published on https://programmingwithmosh.com/
Hooks is a fairly newer concept in React, and the official React documentation does not recommend that you rewrite all your components using Hooks. Instead, you can start writing your newer components using Hooks.
If you want to play with the code samples I used in this blog post, they are available on my GitHub Repo below:
Resources:
There are other hooks in addition to the useContext hook, that we will cover in another blog post. I hope you enjoyed this post. Please share it and you can follow me on twitter at @AdhithiRavi