React.js: the most efficient way to pass a parameter to an event handler without bind() in a component

Instead of .binding or creating an anonymous arrow function in render(), you can create the bound/anonymous function outside of render(), such as on the instantiated object, in the constructor, or something like that, and use a reference to that singular (never re-created) function. For example, run once:

this.boundHandleClick = this.handleClick.bind(this, 111);

or

this.boundHandleClick = () => this.handleClick(111);

Then, in render, reference boundHandleClick:

return (
  <div className="App">
    <button onClick={this.boundHandleClick}>Click</button>
  </div>
);

If you need to use the parameters (111) inside of render, then you could use object lookup to see if a bound function with that parameter exists yet. If it does, just use that bound function – else, create it (once, so it won’t have to be created again whenever you use that parameter in the future):

this.boundClicks = {};
// ...
if (!this.boundClicks['111']) this.boundClicks['111'] = () => this.handleClick(111);
return (
  <div className="App">
    <button onClick={this.boundClicks['111']}>Click</button>
  </div>
);

Leave a Comment