How to use Context API in React

React released the Context API in version 16.3.0. The whole point behind introducing Context API in React is to avoid props drilling to child component. In this article I will try to explain Context API using a very simple example. If you are very new to React, and still trying to understand how props are passed between components, then this article might be too advanced for you.

What Problem are we solving?

When building React application, often we end up in a situation where we have multiple nested components. If a prop has to be passed from a parent component to the last of the child component it has to be passed through each component on the way even thought it might be used in-between.

In the flow Diagram below App is a top level component and User info is a grandchild component. Context API will let you pass props directly from App component to User Info Component without going through the Users Component.

How does Context API work?

Context API works by declaring a global state that can be pulled into any component. Lets see it in action.

Create a context using React.createContext().

Next Step is to create a provider class that will pass your value or state. Notice we’re using our ThemeContext.Provider tag to show this is the component that provides context. Now that context can be used by the consumer class.

Now were are going to import the context in the Content class and use it to do something. Notice we are using ThemeContext.Consumer to import the context into the class.

Here is a CodePen that puts it all together beautifully.

Conclusion

Context API is an excellent way to avoid having nested props drilling allowing us to pass props directly from top component to the bottom component. I am still learning to use Context API is my React best practices to get rid of heavily nested props. Context API can also be used with Hooks to make them even more powerful. In the future I will do a tutorial on Context API + Hooks.

My Stack — React.js, Next.js, Redux.js, JavaScript, GraphQL and Firebase. I also Make youtube videos @Karn Tech

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