Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Context - Context.Consumer vs Class.contextType

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?

like image 965
sgarcia.dev Avatar asked Jan 21 '19 04:01

sgarcia.dev


People also ask

What is contextType in React?

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.

Can we use context Consumer in class component?

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.

Does useContext replace context Consumer?

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.

Which is better useContext or Redux?

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.


1 Answers

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.

like image 185
sgarcia.dev Avatar answered Oct 11 '22 23:10

sgarcia.dev