title: React Typescript - Context in react component class
body: <p>I have created a react typescript app with create react app. I now want to have a context which I want accessible across all my components:</p>
  
  <pre><code>export const UserContext = React.createContext&lt;{name: string}&gt;({name: 'Foo'});
  </code></pre>
  
  <p>The context is linked to the state of the main app component. This state does change and therefore the value of context should also change for the components.</p>
  
  <pre><code>&lt;UserContext.Provider value={this.state}&gt;
      &lt;MainPage/&gt;
  &lt;/UserContext.Provider&gt;
  </code></pre>
  
  <p>I have followed the doc string suggestion for how to set up in context in a component and so have this:</p>
  
  <pre><code>class MainPage extends React.Component {
     static contextType = UserContext;
     context!: React.ContextType&lt;typeof UserContext&gt;;
  
     public render() {
         return &lt;div&gt;{this.context.name}&lt;/div&gt;
     }
  }
  </code></pre>
  
  <p>However <code>this.context.name</code> is always null. I have placed a div with it's value linked to <code>this.state</code> in <em>the app component</em> and that does show the value unlike the context. I am struggling as the code works when written in raw react / create-react-app and I was under the components where the same in <code>@types/react</code>?</p>
  
  <p>Does anyone know how to implement context inside a component class in typescript?</p>