I am learning about the somewhat newly introduced React.Context API, but I've noticed some inconsistencies on it's consumption across examples. Some use the original Context.Consumer HOC method, while some (including the React Docs) use the static Class.contextType method.
What's the difference and why the inconsistency?
The contextType property on a class can be assigned a Context object created by React.createContext() . Using this property lets you consume the nearest current value of that Context type using this.context . You can reference this in any of the lifecycle methods including the render function.
Consuming Context With Class-based ComponentsOne is to use the context from Consumer like “ThemeContext. Consumer” and the other method is by assigning context object from current Context to contextType property of our class. There is always a difference in how we want to use the Context.
The new useContext hook to consume context does not change the concepts surrounding context, hence the plunge above. This context hook only gives us an extra, much prettier, way to consume context. It's amazingly helpful when applying it to components consuming multiple contexts.
Context API is easy to is use as it has a short learning curve. It requires less code, and because there's no need of extra libraries, bundle sizes are reduced. Redux on the other hand requires adding more libraries to the application bundle. The syntax is complex and extensive creating unnecessary work and complexity.
Turns out that the static Class.contextType was newly introduced on React v16.6.0, as the Context.Consumer method proved problematic on class components. Also, there does seem to be one major difference between using both, and it's that the static Class.Context only allows you to subscribe to a single context.
The good news is that both of them seem to reliably listen of Context changes which means if you only have a single Context API, then both are good enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With