Search code examples
reactjsredux

Why do you need to bind a function in a constructor


I have a question relevant to this code: https://github.com/reactjs/redux/blob/master/examples/async/containers/App.js

specifically:

  constructor(props) {
    super(props)
    this.handleChange = this.handleChange.bind(this)
    this.handleRefreshClick = this.handleRefreshClick.bind(this)
  }

I guess its a 2 part question.

  1. Why do I need to set handle change as an instance of class this.handleChange =, can't I just use static functions for handleChange and call it directly with in the class onClick={handleRefreshClick}> ?
  2. I have no idea whats going on here: this.handleRefreshClick.bind(this)

Thanks


Solution

  • Answered in reverse order...

    1. this.handleRefreshClick.bind(something) returns a new function, in which references to this will refer to something. This is a way of saving the current value of this, which is in scope during the call to the constructor, so that it can be used later when the function is called.
    1. If your functions don't require access to the state of your component, then sure, you don't need to bind them.

    The argument in favour of adding these lines to the constructor is so that the new bound functions are only created once per instance of the class. You could also use

    onClick={this.handleRefreshClick.bind(this)}
    

    or (ES6):

    onClick={() => this.handleRefreshClick()}
    

    but either of these methods will create a new function every time the component is re-rendered.