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

1

8

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!

Villiers answered 18/6, 2018 at 12:44 Comment(0)
P
1

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
Probity answered 23/8, 2018 at 15:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.