2

I have a question regarding the object this in class Components.

import React from "react";

class App extends React.Component {
    constructor(props) {
    super(props)
    this.state = {
      count: 0,
      age: 30,
      names: {
        fn: 'Naruto',
        ln: 'Uzumaki'
      }
    };
    this.ref = this.state;
    console.log('constructor');
  }

    update = () => {
        this.setState({ count: this.state.count + 1 });
    };

    render() {
    console.log(Object.is(this.state, this.ref), this.state, this.ref);
    console.log(this.state.names === this.ref.names);
        return <div className="App">
      {this.state.count}
      <button onClick={this.update}>click</button>
      </div>;
    }
}

export default App;

o/p after the initial render:

constructor 
true
{count: 0, age: 30, names: Object}
{count: 0, age: 30, names: Object}
true

o/p after the subsequent renders:

false
{count: 1, age: 30, names: Object}
{count: 0, age: 30, names: Object}
true

false
{count: 2, age: 30, names: Object}
{count: 0, age: 30, names: Object}
true

false
{count: 3, age: 30, names: Object}
{count: 0, age: 30, names: Object}
true

Why the this.ref the points to this.state variable are different in each render after the initial one? If the Objects are merged in by the setState call then this.state and this.ref must be pointing to the same object after each render, right? Can someone enlighten me?

4
  • React state is immutable. Calling this.setState creates a new this.state, it doesn't edit the old one. Commented May 18, 2021 at 3:16
  • Thanks for the answer. Does that mean React maintains its own state object and gives a new state after each render? Commented May 18, 2021 at 3:20
  • Does that mean React maintains its own state object They probably just do something like this.state = {...this.state, ...updatedState}. Ie, overwrite this.state with a new object. Commented May 18, 2021 at 3:22
  • @Vegeta can you mark this as answered? It gives me stack Overflow cred :3 Commented May 19, 2021 at 0:07

1 Answer 1

1

As you can see, Object.is(this.state, this.ref) is returning false after the first change.

This is because once 'setState' is called, the class's state gets set to a new saved 'state' object. This is why you can't update a class's state with this.state.x = val.

If you were to set this.ref=this.state after each set, the two objects WOULD remain the same.

Assume an assign of object.state will always copy what the class's state is at that exact moment

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.