2

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')
  }
}

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

how to check of new instance is actually created.?
I'm sorry, I don't follow this right. Which one is efficient? The first or the second approach ?
@vamshi 1st approach is bad and its answer is it creates the new callback instance every time. But how to check if it creates the new instance every render or not?
@VamshiGudipati i've updated my answer (the first example is considered a bad practice)
@Shubham what do you mean by "how to check if it creates the new instance every render or not?" You are passing a new anonymous (arrow) function on each render, of course it is a new instance. you can't re-use it or call it again when it's anonymous.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.