Its been many years since the accepted answer, and I would like to add some points that were possibly not as clear back in 2014:
Props to purely initialise state
It is considered fine to seed state from special initial state props. In the example above, you would have initialFieldData
class Form extends React.Component {
state = { fieldData: this.props.initialFieldData };
resetFieldData = () =>
setState( () => ({ fieldData: this.props.initialFieldData }));
static getDerivedStateFromProps()
(docs)
React 16.3-alpha introduced the static function, that allows you to map a your regular props to state (to replace componentWillReceiveProps
). A few things to note:
- Importantly this is static function: you can't directly access
this
, but you can access state. In some unusual situations, one might find themselves putting instance values (e.g. refs
) into state, just so they can be accessed there.
- Runs on mount AND each prop change