Skip to content

state property must be defined if getDerivedStateFromProps is used #796

Open
@yourcelf

Description

@yourcelf

It seems that if getDerivedStateFromProps is defined, the component must also initialize its state property. That requirement is undocumented.

The following react component will generate a warning: "MyComponent: Did not properly initialize state during construction. Expected state to be an object, but it was undefined."

class MyComponent extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    return null;
  }
  render() {
    return <span>Foo</span>
  }
}

The warning can be resolved by adding state = {} either in the class definition or the constructor, or by not using getDerivedStateFromProps.

I found this warning confusing:

  • since I'm not overriding the constructor, it's not obvious I'm responsible for initializing state for the construction to work correctly.
  • I can use this.setState without ever having initialized state without warning, so I don't have prior expectations initializing state would be required to use it.
  • Since the only state handling logic for this component comes from getDerivedStateFromProps, I confused the warning with saying that getDerivedStateFromProps was returning undefined.
  • There isn't any documentation in getDerivedStateFromProps or in "State and Lifecycle" that this initialization is required if that lifecycle method is used

I don't know if this is best resolved by making the warning clearer, or documenting the requirement for state initialization either in the docs for getDerivedStateFromProps or in "State and Lifecycle". In hindsight, the warning (while perhaps a little succinct) does indicate what the problem is; it's just that the solution is non-obvious. So I figured I'd open this as a docs issue here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions