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.
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):
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
functional components, so stay tuned :)
If you like to read my blog, you can buy me coffee! :)