How to use React’s Context API (useContext)

Muhammad Basir Baig
2 min readNov 7, 2020

In this article, you will learn how to use React’s Context API which allows you to manage your application’s state globally in your React apps without passing props to your nested child’s components.

Note: Before diving deep, I hope you have basic knowledge of React and JavaScript. I recommend you to take look at React official documentation to have some understanding of React.

What is Context-API ?

If you have some experience with react you may have some issues in passing from top parent state to the nested child component. In React 16.3 React team defines its new Context API to handle the above mentioned problem.
According to the React docs,

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

Let’s Get Started With Context!

1- Create a context with some initial global data which should be shared across react components.

2- Once you initialize the context then in next step to make this context available to all react components, we will wrap our User component with our context provider “UserContext.Provider” so that all our child component can have access to this userContext.

3- We can get the context in any of our child component with useContext hook like this,

As you see in our component we are getting user data from context api and also updating our user data on button click.

Conclusion

In this article, we learned about React’s Context API. Hope you have learned something new today and if you liked this article please make a clap and follow me for more content on Medium. Thanks for reading 🙏 💖.

--

--