Skip to main content
InterviewHubPRO
Section Overview
Q393

Question 393 of 407

Part 9: React Hooks Deep Dive (262 - 316)

97%
React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

How do you use contextType?

mid LevelCode ExampleHooks

ContextType is used to consume the context object. The contextType property can be used in two ways,

vbnet
1.  **contextType as property of class:**
    The contextType property on a class can be assigned a Context object created by React.createContext(). After that, you can consume the nearest current value of that Context type using this.context in any of the lifecycle methods and render function.

    Lets assign contextType property on MyClass as below,
javascript
        class MyClass extends React.Component {
          componentDidMount() {
            let value = this.context;
            /* perform a side-effect at mount using the value of MyContext */
          }
          componentDidUpdate() {
            let value = this.context;
            /* ... */
          }
          componentWillUnmount() {
            let value = this.context;
            /* ... */
          }
          render() {
            let value = this.context;
            /* render something based on the value of MyContext */
          }
        }
        MyClass.contextType = MyContext;
vbnet
2.  **Static field**
    You can use a static class field to initialize default props.