javascriptreactjsreact-16

React 16.4 enables getDerivedStateFromProps to be called from state change. How to cope with that?


So 16.4 "fixes" a bug in getDerivedStateFromProps and now it gets fired both on props change and on state change. Obviously this is intended, coming from this post: https://github.com/facebook/react/issues/12898. However for me, saving previous props in the state is a major overkill, so I am asking if someone has made a procedure in coping with a case like this:

class Componentche extends React.Component {
  state = {
    valuesForInput: {
      input1: ''
    }
  }
  static getDerivedStateFromProps(props, state) {
    if (props.someInitialValuesForInput.input1 !== state.valuesForInput.input1) {
      return {
       valuesForInput: {
         ...state,
         input1: props.someInitialValuesForInput.input1
       }
      }
    }
   return state;

   render () {
      <Input value='valuesForInput.input1' onChange='(e) => setState({valuesForInput: {...this.state, input1: e.target.value }})'
   }
}

So in this above case, I will never ever have change in the input, because getDerivedStateFromProps will execute both on new props received and on the setState trigger, and my condition will never even be false.

So what is the correct way to handle this situation? Do I need to really keep the old props in the state and use them for conditions as well?

I just saw this post from React but they do not offer a working alternative.

Thanks for your help!


Solution

  • The main idea to cope with such a problem is always using one source of truth.

    Actually they provide 2 recommended solutions which don't use getDerivedStateFromProps at all in that blog post:

    1. Fully controlled component
    2. Fully uncontrolled component with a key

    as well as 2 alternatives:

    1. Use extra prop to track in getDerivedStateFromProps
    2. Use instance method in combination with ref