`state` property must be defined if `getDerivedStateFromProps` is used
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 11.8k
- Forks
- 7.9k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 11
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the getDerivedStateFromProps documentation and the “State and Lifecycle” section mentioned in the issue. Confirm how state initialization is described, then clarify that components using this lifecycle must initialize state; done when the requirement and resolution are documented in the relevant guidance.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, react
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100