How do i use componentWillReceiveProps() correctly?

All we need is an easy explanation of the problem, so here it is.

I’m trying to update a child component as soon as it recieves new props. However, componentWillReceiveProps() in my child component is called before the props have actually updated. After reading this article i do understand why but it doesn’t explain me how to solve my problem.

How do i call componentWillReceiveProps() after the props have updated?

Right now i’m cheating my way around it by letting a timeout run which waits for the actual update, but i really don’t like this solution.

  componentWillReceiveProps(){
   var timeOut = setTimeout(() => this.loadPosts(), 100)
  },

Thanks id advance!

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Is it necessary to call componentWillReceiveProps after the props have updated? Or can you use the nextProps argument?

Eg. if you rewrite as:

componentWillReceiveProps(nextProps){
  this.loadPosts(nextProps)
},

and then of course also rewrite the signature of loadPosts to allow manually passing in props:

loadPosts(props = this.props){
  // do something with props
  ...
}

Method 2

Use componentDidUpdate(prevProps, prevState). When it’s called, two arguments are passed: prevProps and prevState. This is the inverse of componentWillUpdate. The passed values are what the values were, and this.props and this.state are the current values.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply