Refactor componentWillReceiveProps() to getDerivedStateFromProps() in React 16.3

Share this video with your friends

Send Tweet

The componentWillReceiveProps() method is being deprecated in future version of React (17). Many of us use this method day-to-day to check for incoming prop changes, store state, and to invoke side effects like logging or fetching data from a server.

In this lesson, we'll look at how to refactor an existing component that uses componentWillReceiveProps() to instead use getDerivedStateFromProps() and componentDidUpdate().

Additional Resources: https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#migrating-from-legacy-lifecycles

~ 6 years ago

Hello, Andrew, Looks like this scenario is breaking in higher versions of React (16.4.1) and React-dom("^16.4.1").

Andrew Del Prete
Andrew Del Prete(instructor)
~ 6 years ago

Hello, Andrew, Looks like this scenario is breaking in higher versions of React (16.4.1) and React-dom("^16.4.1").

Thanks for letting me know. I'll see what I can do to at least fix the example and explain what happened.

Jan Machycek
Jan Machycek
~ 6 years ago

Hi Andrew, this piece of code should definitely be refactored.

componentDidUpdate(nextProps) {
    const { number } = nextProps;
    if (this.state.computedMessage === null) {
      fakeServerRequest(this.props.number).then(result => {
        this.setState({ computedMessage: result });
      });
    }
  }
  1. componentDidUpdate doesnt receive "nextProps" but "prevProps", this can be confusing to some people

  2. you are assigning a variable "number" which you are not using - instead you are correctly using this.state.number which is the "newest" prop, since CDU receives prevProps

Andrew Del Prete
Andrew Del Prete(instructor)
~ 6 years ago

Hey Jan, thanks for the comment. I made some adjustments to the attached CodeSandbox. Good Catch!

Also, as the previous commenter mentioned above, getDerivedStateFromProps() changed significantly in 16.4.x. All updates will fire the getDerivedStateFromProps() even if props don't change. I haven't fixed this in this video since it's specifically for 16.3, but wanted to make sure folks know that this lifecycle method changed quite a bit. Thanks again!