Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does react call render function if I have not changed the reference of the state? [duplicate]

Tags:

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?

like image 692
Alin Ciocan Avatar asked Sep 11 '18 09:09

Alin Ciocan


1 Answers

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.

like image 198
Shubham Khatri Avatar answered Sep 28 '22 18:09

Shubham Khatri