Sung Won Cho Sung Won Cho -4 years ago 294
React JSX Question

React performance: bind vs anonymous function

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download