Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 291
Christopher Francisco Avatar asked Nov 01 '18 22:11

Christopher Francisco


People also ask

Can React context be used with class components?

React Context API provides first class support for class components. To use React Context, we use the Provider component to provide the shared data. In order to subscribe to the Context in class components, we use the contextType property of a class.

How do you use contextType?

contextType = MyContext; The contextType property on a class can be assigned a Context object created by React. createContext() . Using this property lets you consume the nearest current value of that Context type using this.

What is the difference between useContext and context API?

The Context API in React provides you with built-in functions and components to avoid prop-drilling in your component tree. The React Hook useContext() applies the same functionality in a streamlined, functional component body in one call.

Does New React context API trigger re renders?

The updates to context values doesn't trigger re-render for all the children of the provider, rather only components that are rendered from within the Consumer, so in your case although number component contains the Consumer, Number component isn't re-rendered, rather just the render function within the Consumer and ...


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.

like image 121
Christopher Francisco Avatar answered Oct 23 '22 05:10

Christopher Francisco