11

I would like to know if there is a performance difference between using bind and an anonymous function in React components.

Concretely, is one of the following more performant than another?

const MyComponent = ({ myHandler }) => {
  ...
  return (
    <a onClick={myHandler.bind(this, foo, bar)} ...>
      hello world
    </a>
  );
}

const MyComponent = ({ myHandler }) => {
  ...
  return (
    <a
      onClick={() => {
        myHandler(this, foo, bar)
      }
      ...
    >
      hello world
    </a>
  );
}

This question is different from the possible duplicate because the answer to the possible duplicate question focuses on the memory footprint.

mc9
  • 6,121
  • 13
  • 49
  • 87
  • Possible duplicate of [Lambda functions vs bind, memory! (and performance)](http://stackoverflow.com/questions/42117911/lambda-functions-vs-bind-memory-and-performance) – Tatsuyuki Ishi Mar 23 '17 at 00:09
  • Neither: if you need to create an anonymous function to handle an event it's a strong signal that part of the current component need to be extracted to a new component. With all of the handler parameters to be the new component props. – zerkms Mar 23 '17 at 00:21

2 Answers2

11

First off, the way you are setting your question is a bit erraneous:

Your first example <a onClick={myHandler.bind(this, foo, bar)} ...> creates a new function on each render that is bound to the context of the component and always has foo and bar as the first two arguments.

Your second example <a onClick={() => myHandler(this, foo, bar)} ...> instead calls myHandler with 3 arguments, this, foo and bar, where this represents the component context.

On the theoretical level you're discussing about two concepts: is binding this to the function more expensive than creating a new anonymous bound function and calling the function there? I would say that both approaches are very similar from the performance point of view: you're creating a new function (func.bind docs) in both cases.

Any performance differences would be so small that you likely will never develop such a performance-critical piece of software where choosing between () => {} and bind would be an issue.

If you wish to enhance performance here, opt to use a class and bind the click handler to the context in the constructor. That way you do not need to create a new function every time you render.

Hope this helps

jakee
  • 18,486
  • 3
  • 37
  • 42
4

If there is a difference, the difference will be so small that I would be very surprised if you were able to contrive a test where it's even measurable, let alone ever noticeable. Go with the version that's easier for you and other people in the same code base to understand.

Ehren Murdick
  • 426
  • 3
  • 8