Shubham
Shubham

Reputation: 1191

React JS binding callbacks

How can we practically prove the point, After Every render react creates new callback arrow function so it is a bad approach. See below code -

class DankButton extends React.Component {
  render() {
    // Bad Solution: An arrow function!
    return <button onClick={() => this.handleClick()}>Click me!</button>
  }

  handleClick() {
    this.logPhrase()
  }

  logPhrase() {
    console.log('such gnawledge')
  }
}

Also, how the below Arrow function class property function really works ?

class DankButton extends React.Component {
  render() {
    return <button onClick={this.handleClick}>Click me!</button>
  }

  //  ES6 class property-arrow function! 
  handleClick = () => {
    this.logPhrase();
  }

  logPhrase() {
    console.log('such gnawledge')
  }
}

Upvotes: 2

Views: 93

Answers (2)

Andrew
Andrew

Reputation: 7545

Arrow function class property function really works.

Sorry, Don't know how to prove the new instances of function when using bind, but I can do the latter.

console.log this in your arrow function, and compare it to one that is done as a regular function. Do not use bind at any point. The arrow function's this will be the component's context, while the function based one will be either window or undefined.

Upvotes: 0

Sagiv b.g
Sagiv b.g

Reputation: 31024

I'm not sure i understand what you mean exactly by

How can we practically prove the point

As i understand from your question, i assume that you do realize that in the first example above, a new instance of a function is being created.
With that in mind, when you think about it, there are at least 2 issues when you create and pass a new instance of an object or function:

  1. Maybe less important in most cases, you consume more memory on each render.

  2. More important (in my opinion) you can potentially interrupt the Reconciliation and Diffing Algorithm of react by passing a new prop on each render, this will cause a re-render of the child component, hence performance issues can arise.

Upvotes: 1

Related Questions