2

My Application is using React 15 and we are avoiding usages of componentWillReceiveProps in components(so that it is less work at time of migrating to React 16+). Keeping this in mind, the appropriate place to set State based on previous props is componentDidUpdate. But with linter rule react/no-did-update-set-state we are getting below error:

error Do not use setState in componentDidUpdate react/no-did-update-set-state

From the explanation given https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md, rule makes sense.

What is alternative(without disabling rule)... means where should we set state to abide by this rule?

mukesh210
  • 2,792
  • 2
  • 19
  • 41
  • `getDerivedStateFromProps`? It's not perfect but it depends on your usage case – blits Nov 25 '19 at 10:46
  • @blits `getDerivedStateFromProps` isn't available in React 15. – mukesh210 Nov 25 '19 at 10:48
  • the rule you are using is supposed for React 16, not 15. In your case, I'd disable this rule until you migrate to React 16. – blits Nov 25 '19 at 10:50
  • @blits https://reactjs.org/blog/2018/03/29/react-v-16-3.html was written on 29th March,2018. Whereas https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md was modified on 27th oct, 2017. So, there would be some reason for it. – mukesh210 Nov 25 '19 at 10:53
  • fair point, but it's not always replaceable. This rule was created to avoid repetitious renders. If it's some network request you should just go with it, there's no alternative because it will update the state anyway. – blits Nov 25 '19 at 10:58

1 Answers1

0

You can try getDerivedStateFromProps.

  static getDerivedStateFromProps(props, state) {
    if (props.value) {
      return { ...state, value: props.value };
    }
    return state;
  }

In this case if you will receive new value from props, it will be applied to your state.
But react has this hook only with version 16.
In v15 you have to do it with componentWillReceiveProps or componentDidUpdate + setState. There is no other ways.

nickbullock
  • 6,424
  • 9
  • 27