-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Description
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
statefor the construction to work correctly. - I can use
this.setStatewithout ever having initializedstatewithout 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 thatgetDerivedStateFromPropswas returning undefined. - There isn't any documentation in
getDerivedStateFromPropsor 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.