How to use Context API in React

Karn
2 min readOct 22, 2020

--

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().

const ThemeContext = 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.

const Blog = () => (
<ThemeContext.Provider value="#31B7DA">
<Post />
</ThemeContext.Provider>
);

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.

const Content = () => (
<ThemeContext.Consumer>
{ primaryColor => <h1 style={{color: primaryColor}}>Headline</h1> }
</ThemeContext.Consumer>
);

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.

--

--

Karn
Karn

Written by Karn

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

No responses yet