1

I would like to know, which is the correct method to set state of an object in ReactJS.

Please find my sample code:

class MyComponent extends Component {
  constructor(props) {
    this.updateName = this.updateName.bind(this);
    this.state = {
      name: "Sample code"
    };
  }
  updateName() {
    this.setState(name: "Updated");
  }
  componentDidMount() {
    this.updateName();
  }
  render() {
    return (
      <div>
        <label>{this.state.name}</label>
      </div>
    );
  }
}

This is my sample code to update name. Here, name is updated using setState and results in the output 'Updated'.

If updateName() is rewritten as,

updateName(){
  this.state.name = 'Updated';
}

and then printing the name, it gives the same result. I would like to know, the correct method to set the state of an object in ReactJS

Tholle
  • 108,070
  • 19
  • 198
  • 189
SREELAKSHMI R
  • 21
  • 1
  • 6

2 Answers2

2

You should not mutate the state object directly by assigning a new value to this.state.name. You should use the setState method and give it an object that should update the state.

class MyComponent extends Component {
  constructor(props) {
    this.updateName = this.updateName.bind(this);
    this.state = {
      name: "Sample code"
    };
  }

  componentDidMount() {
    this.updateName();
  }

  updateName() {
    this.setState({ name: "Updated" });
  }

  render() {
    return (
      <div>
        <label>{this.state.name}</label>
      </div>
    );
  }
}
Tholle
  • 108,070
  • 19
  • 198
  • 189
0

The correct way to update the state is with this.setState function.

updateName() {
   this.setState(oldState, {...oldState, name: "new name"});
}

ref: https://reactjs.org/docs/state-and-lifecycle.html

Rafael Lima
  • 509
  • 5
  • 13