React: passing value to setState

Refer to lesson: https://www.freecodecamp.org/learn/front-end-libraries/react/create-a-controlled-input

Hi. In the React lesson, it was stated that its better to pass a function value to setState() rather than object only. so instead of this:

handleChange(event) {
    this.setState({
      input: event.target.value
    });
}

I used this

handleChange(event) {
    this.setState(state =>({
        input: event.target.value
    }));
}

But, it didn’t allow me to alter the text area and it throws error in the console log. Also, it passes the test despite the bug. Obviously, passing setState() with a function value isn’t always the best case than passing it with raw Object.

So. What is it that is happening behind when you pass a function value to setState versus passing it a raw object value? And, How will I know which way to use?

The React docs explain it pretty well.


1 Like