So why does react calls render in this scenario:
class MyComponent extends React.Component {
constructor(props) {
this.state = {
user: { name: 'john' },
};
}
render() {
return (
<div>
Name: {this.state.user.name}
<button onClick={() => {
const user = this.state.user;
user.name = 'Michael';
// this works, also this.setState({}) with empty json works too
this.setState({ user });
}}> Change name </button>
</div>);
}
What I was expecting was for React to not detect any changes and in order for the above code to work to make a copy of the user object in order for React to detect the change like this:
const user = {...this.state.user}; // a new copy of object, so new refference
Any ideas?
Setting of state with empty object works because react doesn't do anything with the state mutation itself. Rather it just uses the state object and creates the updated Virtual DOM while the render method is called, which reflects the state mutations too.
However, the problem in doing the state mutation is that the lifecyle methods will now not be able to clearly differentiate between prevState
and this.state
and a lot of comparisons will fails since prevState
and this.state
values will both refer to the same reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With