Props in Initial State

From docs:

Using props to generate state in getInitialState often leads to duplication of “source of truth”, i.e. where the real data is.
This is because getInitialState is only invoked when the component is first created.

The danger is that if the props on the component are changed without the component being ‘refreshed’,
the new prop value will never be displayed because the constructor function (or getInitialState) will never update the current state of the component.
The initialization of state from props only runs when the component is first created.

Bad

  1. class SampleComponent extends Component {
  2. // constructor function (or getInitialState)
  3. constructor(props) {
  4. super(props);
  5. this.state = {
  6. flag: false,
  7. inputVal: props.inputValue
  8. };
  9. }
  10. render() {
  11. return <div>{this.state.inputVal && <AnotherComponent/>}</div>
  12. }
  13. }

Good

  1. class SampleComponent extends Component {
  2. // constructor function (or getInitialState)
  3. constructor(props) {
  4. super(props);
  5. this.state = {
  6. flag: false
  7. };
  8. }
  9. render() {
  10. return <div>{this.props.inputValue && <AnotherComponent/>}</div>
  11. }
  12. }