In the reactjs 16... version, the contextType property was added, and also the use of functional components was encouraged. but for some reason, there doesn't seem to be any documentation about using both of them together. The only examples found are those of using contextType in a combination with a class component. Does anyone have an example of using contextType in a functional component structure?
Use the useContext()
hook. From the React docs:
Tip
If you’re familiar with the context API before Hooks,
useContext(MyContext)
is equivalent tostatic contextType = MyContext
in a class, or to<MyContext.Consumer>
.
useContext(MyContext)
only lets you read the context and subscribe to its changes. You still need a<MyContext.Provider>
above in the tree to provide the value for this context.