Search code examples
javascriptreactjsreact-nativegetderivedstatefrompropscomponentwillreceiveprops

how to use getDerivedStateFromProps instead of componentWillReceiveProps in React


I like to update my code to use getDerivedStateFromProps instead of componentWillReceiveProps as the I am receiving deprecated error. The component is receiving a date prop and every time the date is changed in need to run the getList with the new date. To do this I am using the follow code below

componentWillReceiveProps(nextProps) {
    const {date} = this.props;
    if (nextProps.date !== date) {
      console.log('prop changed to : ', nextProps.date);
      this.getList(nextProps.date);
    }
  }

I tried the following but it does not work

static getDerivedStateFromProps(props, state) {
    const {date} = this.props;
    if (props.date !== date) {
      console.log('prop changed to : ', props.date);
      this.getList(props.date);
    }
    return;
  }

Solution

  • getDerivedStateFromProps does not look like the right tool for what you are trying to do. Instead use componentDidUpdate:

    componentDidUpdate(prevProps) {
      const { date } = this.props;
      if (prevProps.date !== date) {
        this.getList(date);
      }
    }
    

    It's pretty rare to use getDerivedStateFromProps. For more information on when to use getDerivedStateFromProps I recommend this article