Reputation: 6349
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.
Upvotes: 11
Views: 4024
Reputation: 18556
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
Upvotes: 11
Reputation: 436
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.
Upvotes: 4