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?
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.
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.
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.
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 ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With