contextType
Learn how to access values from Context Providers by using the contextType property instead of making a separate Consumer component.
We'll cover the following
Why use contextType
?
While using class components, we can employ a trick that allows us to avoid building another Consumer component bloating our component tree further.
To do this, we can use contextType
. It can be assigned to a class component in the form of a static property. The Context value can then be accessed within the component via this.context
. The value of the contextType
property is created by React.createContext()
, which you need to call beforehand.
But be careful. It is only possible to assign a single Context type to a class. If we want to access two or more Contexts, we have to wrap the respective JSX in a Consumer component. By using Public Class Fields Syntax from ES2015+, it is sufficient to define a static class property contextType
and to assign it a Context.
If applied to our previous Translated
component, the result would be:
class Translated extends React.Component {
static contextType = LanguageContext;
render() {
return this.context.translations[this.props.translationKey];
}
}
Code example
The value of the current LanguageContext
is assigned to the static contextType
property of the component (which is now a class component). Its value can be read by accessing this.context
. Let’s see this in action.
Get hands-on with 1200+ tech skills courses.