Here is a good (slightly old) article that discusses initialising state with props:
https://medium.com/@justintulk/react-anti-patterns-props-in-initial-state-28687846cc2e
The React docs call this an anti-pattern:
"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."
From the docs, there is an exception to this which is:
"Only use this pattern if you intentionally want to ignore prop updates. In that case, it makes sense to rename the prop to be called initialColor or defaultColor. You can then force a component to “reset” its internal state by changing its key when necessary."
That being said, I also find myself doing this from time to time.
An example where I find it useful is components that allow users to edit complex state. You can initialise the state with props and the component internally handles changes to this state. If you want to reset the state when the props change, you have two options:
The first is to listen for changes and call setState like:
componentDidUpdate(prevProps, prevState) {
if (prevProps.inputValue !== this.props.inputValue) {
this.setState({ inputVal: this.props.inputValue })
}
}
The recommended option is to give the component a key which depends on the props that should trigger a reset. Then when the props change, the component state will be re-initialised:
<MyComponent initProp={someValue} key={`key_${someValue}`/>
I would only recommend these options for complex state. In most examples the parent component could hold this state and the inner component could use a callback to to update the parent with changes.