Home > database >  What is the diff between this two arrow functions?
What is the diff between this two arrow functions?

Time:02-18

Basically, I don't understand why the second arrow function works, and first doesn't.

    //this one doesnt
    this.setState = () => {
            text: e.target.value,
        };
  
    //this one works
    this.setState(() => ({
            text: e.target.value,
        }));

CodePudding user response:

The first one is an assignment the second one performs execution.

CodePudding user response:

The first one assigns the arrow function to this.setState and since there is an existing function called setState on this, it'll be overwritten by your arrow function.

The second one passes the arrow function as an argument to setState and setState will call the function you just passed at some point in its execution.

You can refer to the documentation to get a better idea of what setState does.

https://reactjs.org/docs/react-component.html#setstate

  • Related