Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react 'componentWillReceiveProps' use

I'm new to React and I'm going through the lifecycles of React, however I'm little bit confused with the use of componentWillReceiveProps.

Can anyone explain me in which case it should be used.

Thanks.

like image 281
OmkarS1109 Avatar asked Dec 12 '18 10:12

OmkarS1109


2 Answers

This method is called when props are passed to the Component. can be used to update the internal state of the component from newly received props.

Please refer to this link for better understanding. https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/component_will_receive_props.html

however, it is deprecated in React 16.

like image 189
Kishan Rajdev Avatar answered Oct 17 '22 04:10

Kishan Rajdev


So, componentWillReceiveProps is invoked everytime your component receives new props, it's used to update the state of the component.

So for example:

export default class ExampleComponent extends Component {
  constructor(props) {
    super(props);

    state = {
      stateExample: this.props,
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props !== nextProps) {
      this.setState(nextProps)
    }
  }
}

Please note that componentWillReceiveProps is deprecated since react 16. You should start using getDerivedStateFromProps. On the same example above, it would be like this:

static getDerivedStateFromProps(nextProps, prevState) {
  if(nextProps.stateExample !== prevState.stateExample) {
    return { stateExample: nextProps.stateExample }
  } else return null;
}
like image 36
kivul Avatar answered Oct 17 '22 02:10

kivul