Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does React bind this in setState callback?

I was expecting to see undefined being logged when the "Without binding" button was clicked because when you pass a method reference plainly as a callback, it shouldn't be called with the right this context, but with an arrow function, it should.

However, I saw that the callback function could access this and the value of this.state.number was logged properly. The method reference and arrow function performed the exact same. Why?

This does not have to do with arrow function class properties, it has to do with passing a reference to a method as a callback to setState as opposed to an arrow function.

class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      number: 1,
    };
  }

  onClickWithThisBindingInCallback = () => {
    this.setState({ number: 2 }, () => { this.myCallback(); });
  };

  onClickWithoutThisBindingInCallback = () => {
    const myCb = this.myCallback;
    this.setState({ number: 3 }, myCb);
  };

  myCallback() {
    console.log(this.state.number);
  }

  render() {
    return (
      <div className="App">
        <button onClick={this.onClickWithThisBindingInCallback}>With binding</button>
        <button onClick={this.onClickWithoutThisBindingInCallback}>Without binding</button>
      </div>
    );
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>
like image 236
Yangshun Tay Avatar asked Nov 18 '22 23:11

Yangshun Tay


1 Answers

React calls the callback function of setState with the component's instance this, as seen by this line of code.

Credits: @Li357

like image 97
Yangshun Tay Avatar answered Dec 15 '22 09:12

Yangshun Tay