2

I found a tutorial online regarding on React.js but I saw the way the tutor did where he change the state without setState() function. I am here asking whether it is a good practice.

The constructor:

constructor(props) {
    super(props);
    this.state = {
      uid: uuid.v1(),
      name: '',
      answers: {
          answer1: '',
          answer2: '',
          answer3: ''
      },
      isSubmitted: false
    };
    this.onSubmit = this.onSubmit.bind(this);
    this.answerSelected = this.answerSelected.bind(this);
    this.questionSubmitted = this.questionSubmitted.bind(this);
}

The way he update the state is:-

answerSelected(event) {
    let answers = this.state.answers;
    if (event.target.name === 'answer1') {
        answers.answer1 = event.target.value;
    } else if (event.target.name === 'answer2') {
        answers.answer2 = event.target.value;
    } else if (event.target.name === 'answer3') {
        answers.answer3 = event.target.value;
    }
}

From what I know, React should set state by using setState({answers: {answer1: event.target.value}}). Am I right? What is the better approach?

johnson lai
  • 996
  • 1
  • 11
  • 15

1 Answers1

3

Setting/Changing state inside react component always should be using setState, this is what react recommends. The only place where state can directly be modified is the constructor. Read more here.

Also worth reading this

Umesh
  • 2,704
  • 19
  • 21