How do you use contextType?

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

  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,

    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;
  2. Static field You can use a static class field to initialize your contextType using public class field syntax.

    class MyClass extends React.Component {
    static contextType = MyContext;
    render() {
    let value = this.context;
    /* render something based on the value */
    }
    }

April 30, 2022
287