Skip to main content

Command Palette

Search for a command to run...

What is contextType in React?

Updated
•2 min read•View as Markdown
What is contextType in React?
O

I am web developer / front-end engineer from Germany. My stack includes:

  • HTML and CSS (including SASS, Tailwind, MaterialUI, Bootstrap)
  • JavaScript
  • ReactJS
  • WordPress
  • Git

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 :)

More from this blog

O

Olena Drugalya's Blog

28 posts

Web Developer/ Blogger/ Front-End Engineer