score:4

Accepted answer

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.

score:2

componentwillreceiveprops is currently deprecated as of 16.3.0 onwards. however before this version, you would perform side-effects as well as update state based on change in props received by your component. you can still use this lifecycle method for the same purpose but its better to follow the latest practice.

as of react docs:

using this lifecycle method often leads to bugs and inconsistencies

  • if you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use componentdidupdate lifecycle instead.
  • if you used componentwillreceiveprops for re-computing some data only when a prop changes, use a memoization helper instead.
  • if you used componentwillreceiveprops to “reset” some state when a prop changes, consider either making a component fully controlled or fully uncontrolled with a key instead.

from v16.3.0 onwards, its recommended to perform side-effects in componentdidupdate in response to props/state change and use memoization/getderivedstatefromprops to set state based on props change.

for more information you must refer the react docs

score:2

you can use it, if you need to rewrite the component after reaching props you needed

read this, might help

will componentwillrecieveprops run every time props are received

score:4

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;
}

Related Query

More Query from same tag