1

Could you please explain to me why we need to bind “this” in our own declared methods in React class components? I do understand that the value of “this” depends on the environment where “this” is being used. However, in the code below we have 3 methods - constructor(), changeText() and render(). Why “this” works just fine in constructor() and render() but doesn’t work in my own method - changeText() unless I bind it? I have read a lot of articles on “this” but still don’t understand why our own methods should be bound to “this”…

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      text: "Change Text",
    };
    this.changeText = this.changeText.bind(this);
  }

  changeText() {
    this.setState({
      text: "Text Changed",
    });
  }

  render() {
    return (
      <div>
        <div>
          <h3>{this.state.text}</h3>
          <button onClick={this.changeText}>Click Me</button>
        </div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

DmitryDev
  • 123
  • 3
  • 7
  • 1
    *"I do understand that the value of “this” depends on the environment where “this” is being used."* Not usually. In a traditional (non-arrow, unbound) function it depends on *how the function was called*. See [this question's answers](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) for details on that, or my [very old blog post](http://blog.niftysnippets.org/2008/04/you-must-remember-this.html). :-) You have to bind because the way React calls them doesn't set `this`. You don't have to in the constructor or `render` b/c React *does* set `this` when calling those. – T.J. Crowder Jun 14 '20 at 11:50
  • 2
    The natural follow-on question is then: *"**Why** doesn't React set `this` when calling event handlers?"* The answer is that they aren't necessarily methods of the class. If React set `this` to the instance when calling event handlers, it would be assuming all handlers are from the class's methods and not (for instance) things received as props, or other standalone functions, etc. There are other design choices they could have made; this is the one they *did* make. :-) – T.J. Crowder Jun 14 '20 at 11:56

0 Answers0