2

I am trying to migrate my apps to do the React v16.3.* API, and it has been quite difficult to get rid of componentWillReceiveProps. I have components which are dependent on it and call the components other function in them.

Because getDerivedStateFromProps is static, I can't easily do this anymore and I need help on how to appropriately. For this case in particular, I have a timeout function that resets whenever new props are received. It currently is as follows:

componentWillReceiveProps (nextProps) {
  clearTimeout(this.timeout)
  this.timeout = setTimeout(() => {
    this.dismiss(null, nextProps)
  }, nextProps.timer)
}

As you can see I have this.timeout and this.dismiss which I cannot access anymore once the change is made to getDerivedStateFromProps. How to I deal with this? Is there a way to change this to be a getDerivedStateFromProps static function or do I have to go about this a completely different way?

theJuls
  • 6,788
  • 14
  • 73
  • 160
  • 2
    `getDerivedStateFromProps` is about whether or not state needs to be updated based on nextProps. There's no state updating in your example. If that is the case in your actual code, you could just use `componentDidUpdate` and operate on `this.props` instead of `nextProps`. – Kyle Richardson Apr 17 '18 at 21:31
  • I hadn't realized I could use componentDidUpdate as a fine replacement for this particular case. Now I feel silly. Thanks! – theJuls Apr 18 '18 at 14:21

1 Answers1

2

As @Kyle mentions, this doesn't belong in getDerivedStateFromProps, but it might not be immediately obvious why you can safely do this in componentDidUpdate.

The reason you can is that you're only clearing and setting timers, which won't affect anything until after React has updated the DOM and finished executing. Hence, it makes no difference if you do this in the pre-render componentWillReceiveProps or the post-update componentDidUpdate:

componentDidUpdate()
  clearTimeout(this.timeout)
  this.timeout = setTimeout(() => {
    this.dismiss(null, this.props)
  }, this.props.timer)
}

The React blog has some example migrations that may prove helpful.

Ninjakannon
  • 3,751
  • 7
  • 53
  • 76
Oblosys
  • 14,468
  • 3
  • 30
  • 38
  • I hadn't realized that I could for that very reason. Needless to say, it does it's job perfectly. Thanks! – theJuls Apr 18 '18 at 14:23