Initializing the state from the props in the constructor, or as a class property, will not update the state when the prop changes. However, react does detect the prop change, and rerenders the component.
Example:
class AttachStateToProps extends React.Component {
state = {
stateValue: this.props.VALUE,
}
render() {
console.log('Value of Prop - ', this.props.VALUE)
console.log('Value of State - ', this.state.stateValue)
return null
}
}
const renderWithVal = (val) => ReactDOM.render(
<AttachStateToProps VALUE={val} />,
demo
);
renderWithVal(5);
renderWithVal(15);
renderWithVal(115);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="demo"></div>
To update the state when the prop changes, you need to use a component's lifecycle method.
With React ^16.3 you can use the static getDerivedStateFromProps()
method to update the state from the props (and initialize it as well):
static getDerivedStateFromProps(nextProps) {
return {
stateValue: nextProps.VALUE,
}
}
class AttachStateToProps extends React.Component {
state = {};
static getDerivedStateFromProps(nextProps) {
return {
stateValue: nextProps.VALUE,
}
}
render() {
console.log('Value of Prop - ', this.props.VALUE)
console.log('Value of State - ', this.state.stateValue)
return null
}
}
const renderWithVal = (val) => ReactDOM.render(
<AttachStateToProps VALUE={val} />,
demo
);
renderWithVal(5);
renderWithVal(15);
renderWithVal(115);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="demo"></div>
With React versions prior to 16.3, you can use componentWillReceiveProps()
.
Note: componentWillReceiveProps is deprecated, but will work 'till version 17.
componentWillReceiveProps(nextProps, prevState) {
this.setState({
stateValue: nextProps.VALUE,
})
}
true
all the time. Also eslint complains[eslint] Do not use setState in componentDidMount (react/no-did-mount-set-state)
- i think its not a good pattern – Serviceberry