After switching to new Context API in React introduced in 16.3.0, this.context is being shown as deprecated even though the official docs tells you to use it like this:
class MyClass extends React.Component {
componentDidMount() {
let value = this.context;
/* perform a side-effect at mount using the value of MyContext */
}
componentDidUpdate() {
let value = this.context;
/* ... */
}
componentWillUnmount() {
let value = this.context;
/* ... */
}
render() {
let value = this.context;
/* render something based on the value of MyContext */
}
}
MyClass.contextType = MyContext;
The legacy context API will be removed in a future major version. Use the new context API introduced with version 16.3. The legacy API will continue working for all 16.
Before You Use Context Apply it sparingly because it makes component reuse more difficult. If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context.
The deprecation message is actually a bug and someone already submitted a patch to fix it.
The contextType property is used to consume a context created with React. createContext() . When the property is specified for a React component, you can access the current value of the context using this. context inside lifecycle methods of the component.
Using context API like you have used in your case is Supported before version 16.3.0 and post 16.6.0.
The API changed a bit between 16.3.0 to 16.6.0 where you need to use a Consumer render prop pattern but was later refined to support the contextType pattern to allow usage of Context in lifecycle method
If you are using the API like you mentioned above, please make sure that you are using a version of React above 16.6.0
If you are using version betwee 16.3.0 to 16.6.0, use Context like
class MyClass extends React.Component {
componentDidMount() {
let value = this.props.context;
/* perform a side-effect at mount using the value of MyContext */
}
componentDidUpdate() {
let value = this.props.context;
/* ... */
}
componentWillUnmount() {
let value = this.props.context;
/* ... */
}
render() {
let value = this.props.context;
/* render something based on the value of MyContext */
}
}
export default (props) => (
<MyContext.Consumer>
{(context) => <MyClass {...props} context={context}/>}
</MyContext.Consumer>
)
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