What is contextType in React?

Subscribe to my newsletter and never miss my upcoming articles

In my previous blog about Context API we went through creating and implementing Context API object for state management. This blog is about another more elegant way of using Context.

What is contextType?

React 16.6 introduced a new feature for class-based components to get access to Context without Context.Consumer component. To understand better, lets remember how we use Consumer:

contextType_consumer.png

To use the new way, at the top of the class we declare a static property called contextType and set it equal to the full user context:

static contextType = MyContext;

It has to be written exactly like this - contextType- and it has to be static (static means this property can be accessed from outside without the need to instantiate an object based on this class first).

This allows React to automatically connect this class component to context and it gives you a new property - this.context property, which we can use (for example, we can log it now):

console.log(this.context.authenticated);

Now we can access our context in the places we previously couldn't. And of course we can use it in the render() function:

contextType_final.png

This property can be used only in class-based components and its recommended to use because its shorter and easier and context can be accessed anywhere. In my next blog we are going to talk about avoiding context.Consumer in functional components, so stay tuned :)

No Comments Yet