Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs, this.context is deprecated

Tags:

reactjs

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;
like image 942
Anish Shrestha Avatar asked Nov 20 '18 06:11

Anish Shrestha


People also ask

Is context API deprecated?

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.

What's wrong with using context in React?

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.

Why is Super deprecated in React?

The deprecation message is actually a bug and someone already submitted a patch to fix it.

What is contextType in react JS?

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.


1 Answers

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>
)
like image 127
Shubham Khatri Avatar answered Sep 19 '22 22:09

Shubham Khatri