React - New Context API not working with Class.contextType, but works with Context.Consumer

Viewed 2970

I'm trying out the new context API using a HOC that returns a wrapped component. It doesn't work when I use the Class.contextType = Context approach:

return function myHOC(WrappedComponent) {
  class HOC extends React.Component {
    // static contextType = MyContext;

    render() {
      console.log(this.context);  // HERE, this logs `{}`

      // ..do stuff
      return <WrappedComponent {...this.props} />
    }
  }
  HOC.contextType = MyContext;

  return HOC;
};

However, I made the same code but using <MyContext.Consumer> and it worked fine:

return function myHOC(WrappedComponent) {
  const HOC = (props) => (
    <MyContext.Consumer>
      {(context) => {
        console.log(context);  // HERE, correct values

        return <WrappedComponent {...props} /> 
      }}
    </MyContext.Consumer>
  );

  return HOC;
};

Am I not seeing something here?

1 Answers

Turns out that even though I updated my react-scripts to 2.0, I had to update react to 16.6 (previously on 16.3) on my own.

I was under the impression react-scripts would also handle the react version. My bad, got confused there.

Related