Updating state with props on React child component
It would also be good to check if you even need to update the state, since this will cause a re-render.
componentWillReceiveProps(newProps) {
if (this.state.name !== newProps.name) {
this.setState({name: newProps.name});
}
}
Calling setState()
in componentWillReceiveProps doesn't cause additional re-render. Receiving props is one render and this.setState would be another render if that were executed within a method like componentDidUpdate. I would recommend doing the this.state.name !== nextProps.name
in shouldComponentUpdate so it's always checked for any update.
componentWillReceiveProps(nextProps) {
this.setState({name: nextProps.name});
}
shouldComponentUpdate(nextProps) {
return this.state.name !== nextProps.name;
}
You need to implement componentWillReceiveProps
in your child:
componentWillReceiveProps(newProps) {
this.setState({name: newProps.name});
}
Edit: componentWillReceiveProps
is now deprecated and will be removed, but there are alternative suggestions in the docs link above.