Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How unperformant are anonymous functions in React component attributes?

You're not supposed to use anonymous functions in react attributes, e.g.

<a onClick=()=>doIt('myId')>Aaron</a>

I understand why this creates a performance problem for React's reconciliation because that anonymous function is recreated on every render pass and will thus always trigger a real DOM re-render of some kind. My question is, for a small component (i.e. not table where every row has a link) is this insignificant? I mean, React is smart enough just to replace the handler, not to re-render the DOM, right? so the cost is not that high?

like image 708
CpnAhab Avatar asked Feb 16 '17 17:02

CpnAhab


2 Answers

I feel obliged to inform you that using an Anonymous function and Function.bind(this) in the render triggers a new render. This is because both

doIt.bind(this, 'myId') === doIt.bind(this, 'myId') // false

AND

() => doIt('myId') === () => doIt('myId') // false  

are FALSE!

If you want to bind something to a function, use partial application with a method in the React class.

class myComponent extends Component {

  doIt = (id) => () => {
    // Do Something
  }

  render() {
    <div>
      <a onClick={this.doIt('myId')}>Aaron</a>
    </div>
  }
}
like image 105
Craig1123 Avatar answered Sep 20 '22 09:09

Craig1123


For:

  • small components: you are ok (almost no performance issues)
  • large components: the deeper you get the more try to avoid it

In React documentation about event handling, you can find:

In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.


Note: React is not handling callback props differently than other props. It always compares the old and new prop. Thus it re-renders when anonymous function is present because the anonymous function is always newly created.

like image 29
exmaxx Avatar answered Sep 18 '22 09:09

exmaxx