React: componentWillReceiveProps doesn't detect when an object prop is mutated

Created on 3 Nov 2015  路  1Comment  路  Source: facebook/react

When passing an object state from owner to child, like this:

getInitialState(): {
    return { obj: {property: null} };
},
mutateState(value) {
    this.setState({
        obj: {property: value}
    });
},
render() {
    return (
        <ChildComponent passedObj={this.state.obj} onChange={this.mutateState}/>
    )
}

<ChildComponent> doesn't detect the change in componentWillReceiveProps

// ChildComponent
componentWillReceiveProps(nextProps) {
      console.log(this.props.passedObj === nextProps.passedObj); // always true
      console.log(this.props.passedObj.property === nextProps.passedObj.property); // also always true
}

It looks like nextProps or this.props is only taking a reference of the passed object. Doing this works:

componentWillReceiveProps(nextProps) {
      console.log(this.prevPassedObj === nextProps.passedObj); // always false
      console.log(this.prevPassedObj.property === nextProps.passedObj.property); // false when it's supposed to be
       this.prevPassedObj = Object.assign({}, nextProps.passedObj);
}

Haven't tried this using a non-state object.

1) Is this React's intended behavior, and 2) should it be?

Most helpful comment

1) Yes, this is intended.

2) Yes, React doesn't do a deep copy of your props. Doing so for every component would be prohibitively slow. If you want this behavior you can copy it yourself (or simply not mutate it in the first place).

>All comments

1) Yes, this is intended.

2) Yes, React doesn't do a deep copy of your props. Doing so for every component would be prohibitively slow. If you want this behavior you can copy it yourself (or simply not mutate it in the first place).

Was this page helpful?
0 / 5 - 0 ratings