How Do You Use contextType in ReactJS?

contextType is a property on a class-based React component that assigns the context object retrieved from React.createContext() to a static property. This allows you to access the context value using this.context within the component.

Here's how you can use contextType in ReactJS:

import React from 'react';

// Create a context
const MyContext = React.createContext();

// Context provider component
class MyProvider extends React.Component {
  render() {
    return (
      <MyContext.Provider value="Hello from Context!">
        {this.props.children}
      </MyContext.Provider>
    );
  }
}

// Consumer component
class MyConsumer extends React.Component {
  render() {
    return (
      <div>
        <h2>Consumer Component</h2>
        <p>Context Value: {this.context}</p>
      </div>
    );
  }
}

// Assign the context type
MyConsumer.contextType = MyContext;

// App component
class App extends React.Component {
  render() {
    return (
      <MyProvider>
        <div>
          <h1>App Component</h1>
          <MyConsumer />
        </div>
      </MyProvider>
    );
  }
}

export default App;

In this example

  1. We create a context using React.createContext() called MyContext.
  2. We define a provider component (MyProvider) that wraps around the parts of the component tree where the context should be available.
  3. We define a consumer component (MyConsumer) that will consume the context value.
  4. Inside MyConsumer, we set the contextType to MyContext. This allows us to access the context value using this.context.
  5. In the App component, we wrap the MyConsumer component with the MyProvider component, establishing the context provider-consumer relationship.

Now, wherever the MyConsumer the component is rendered within the MyProvider component tree, it will have access to the context value provided by MyProvider through this.context

Summary

In ReactJS, contextType is a property utilized in class-based components to subscribe to the context provided by a higher-level Provider component. By setting contextType to a context object created via React.createContext(), the component can access the context's value directly using this.context. This streamlines context consumption within class components, especially in lifecycle methods and event handlers, compared to alternative patterns like render props or higher-order components. However, it's exclusive to class components and supports subscriptions to only a single context per component.