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?

1 Answer 1

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

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.