DEV Community

Cover image for What is contextType in React?
Olena Drugalya
Olena Drugalya

Posted on • Edited on

3 1

What is contextType in React?

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:
Alt Text

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;


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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

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

If you like to read my blog, you can buy me coffee! :)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay