Search code examples
reactjsclassfunctional-programminglifecycle

what is the right way to implement contextType in reactjs functional components?


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?


Solution

  • Use the useContext() hook. From the React docs:

    Tip

    If you’re familiar with the context API before Hooks, useContext(MyContext) is equivalent to static 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.