2

I was reading React facebook's documentation and there it is written that

Invoked when a component is receiving new props. This method is not called for the initial render.

but later in this link, it has been explained that even if the props are same then this method is called because the props can be references and the data at those references might be different.

So, My question is whether it is called every time we receive new props.

Ajay Gaur
  • 5,140
  • 6
  • 38
  • 60
  • 2
    yes. It will get called everytime the component will receive possibly new props. It does not get called on the initial render. – Brandon Mar 15 '16 at 13:12

2 Answers2

7

Initial renders means when your component is loaded first time with whatever data it has. E.g:

Parent
    constructor() {
            super();
            this.state = {
                viewData:undefined,
            };
    componentDidMount(){
      let myData = yourStore.getData();
      this.setState({viewData:myData})
    }
    updateView(){
     let myData = yourStore.getData();
      this.setState({viewData:myData})
    }


render() 
   {
    return(
      <div>
         {
      this.state.viewData && this.state.viewData.map(function (obj, index) {
        return <childComponenet data={obj} key={index}/>
       })
        }       
      </div>
     <button onClick={this.updateView.bind(this)>Update</button>}
     )
}

ChildComponent:

constructor() {
        super();
        this.state = {
            childData:this.props.data
            }
        };

//componentDidMount(){
  //this.setState({childData:this.props.data}) }

componentWillReceiveProps(newProps){
   this.setState({childData:newProps.data})//this method will not get called first time
}

render(){
   return(
   <span>{this.state.childData}</span>
   )
}

Constructor is initialised only once. So when first time child component is rendered, it will set the state variable. Now as you click on update state in parent component, state is updated and it will pass the updated state as props to child component. In this case componentWillReceiveProps method will get called and it update the child component state.

Note: componentWillReceiveProps not checks the internal value of props. It means even though previous and current props is same, it will be in action. Hence the answer is YES. It will get called every time, when it receives new props from parent.

Ved
  • 11,837
  • 5
  • 42
  • 60
  • I didn't have this doubt. I know it won't run first but componentWillReceiveProps(*newProps*) will run every time after that (initial render). – Ajay Gaur Mar 15 '16 at 13:36
1

As suggested by Brandon in comments:

yes. It will get called everytime the component will receive possibly new props. It does not get called on the initial render

Community
  • 1
  • 1
Ajay Gaur
  • 5,140
  • 6
  • 38
  • 60