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

react button onclick link
react pass function as prop
react event target
addeventlistener react
this.props is not a function
react bind event
react bind multiple parameters
react link onclick

When you have to use this keyword within an event handler, you have to bind the function (event handler) with this kerword. Otherwise, you need to use the arrow function.

e.g.

//This function isn't bound whilst using "this" keyword inside of it.
//Still, it works because it uses an arrow function
handleClick = () => {
    this.setState({
      isClicked:true
    });
}

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

However, with the approach above, you can't pass a parameter. You need to use either...

  1. bind(this, param) after the function
  2. the anonymous arrow function

i.e.

<button onClick={this.handleClick}>Click</button>
will be
<button onClick={this.handleClick.bind(this, 111)}>Click</button>
or
<button onClick={() => this.handleClick(111)}>Click</button>

Here is the question.

What is the most efficient way to pass a parameter to an event handler?

According to the official doc, using bind() can undermine the performance, because...

Using Function.prototype.bind in render creates a new function each time the component renders

The same goes for using the anonymous arrow function. The doc says that...

Using an arrow function in render creates a new function each time the component renders

Then, what will be the most efficient way to pass a parameter?

Any input will be appreciated.

PS

Some people have asked how param is determined. This will be determined dynamically (i.e. not always 111). So, it can be from states, props or some other functions defined in this class.


I have explained it in my another post: click event in react component.

Never use inline arrow function if you're worried about its performance. You can still use the public class method and bind the context this.

handleClick = () => () => {
    this.setState({ // this works now
      isClicked:true
    });
}

You can pass any parameters you like just like this:

handleClick = (param1, param2, param3) => (event) => {

As per devserkan's comment,

This is currying and same as other options. This function is also recreated in every render.

No. It doesn't. See the note from docs:

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.

Also, see the comment from bigga-hd below the certainperformance's answer:

Avoid declaring arrow functions or binding in render for optimal performance. Declare your functions outside of render. No more function allocations on each render.


How do you call this handler?

You can call the method just like this:

onClick={this.handleClick(param1,param2,param3)}

PS: I did not mark this post as duplicate as question scope is significantly different. So, just linked the post to get you dig into more detail.

Passing Functions to Components – React, How do I pass an event handler (like onClick) to a component? How do I bind a function to a component instance? class Foo extends Component { // Note: this syntax is experimental and not standardized yet. Generally speaking, yes, it is OK, and it is often the easiest way to pass parameters to callback functions. To then reference our function and pass in our message as the parameter, we use the this.eventhandler.bind(this, parameters), our event handler name, in this case, is displayMessage. This binds the instance of this (the component) to the function, as it is not done automatically by React, thus calling this.props or this.state would result in null.


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>
);

Handling Events – React, In JavaScript, class methods are not bound by default. If you forget to bind this.​handleClick and pass it to onClick , this will be undefined when the function is  We can define the event handler and bind it to this using JavaScript’s Function.prototype.bind() function. If we need to pass custom parameters, then we can simply pass the parameters to the bind call. The SyntheticEvent will be passed as second parameter to the handler. A bind call function in a JSX prop like above will create a brand new function on every single render. This is bad for performance, as it will result in the garbage collector being invoked way more than is necessary.


This depends on how you get the parameter. There will be times you can't avoid using a .bind or an arrow function easily but most of the times you can get the parameter somehow. As you can see in @CertainPerformance's answer if you can use this argument in the constructor, you can prefer this way. But there can be other approaches.

For example, assume that you have a list in the state. Instead of mapping this list directly and using a .bind or an arrow function there, you can pass the list elements to a child component and then use a callback handler there.

class App extends React.Component {
  state = {
    list: [ "foo", "bar" ],
  };

  handleClick(el) { console.log( el ) }

  render() {
    return (
      <div>
        {this.state.list.map( el => (
          <Child key={el} el={el} onClick={this.handleClick} />
        ) )}
      </div>
    );
  }
}

const Child = ( props ) => {
  const handleClick = () => props.onClick( props.el );
  return (
    <div>
      {props.el}
      <button onClick={handleClick}>Click</button>
    </div>
  );
};

ReactDOM.render( <App />, document.getElementById( "root" ) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

ReactJS - Parameterized Event Handlers, It is quite frequent requirement to pass parameters to event handlers of custom and bind it to this using JavaScript's Function.prototype.bind() function. brand new function is passed as a prop to a component that uses reference most concise (not most efficient though) way to define event handlers that  React.js: the most efficient way to pass a parameter to an event handler without bind() in a component 1 How does bind automatically pass the event argument to an event handler?


I used to do this kind of thing for state names. Depends on what you want, you can try this. So that, i don't have to bind the function again. Where you can get state name from e.target.name

class App extends React.Component {
  state = {
    change: ""
  };

  handleChange = e => {
    const { name, value } = e.target;
    this.setState({ [name]: value  })
  };

  render() {
    return (
      <input
        type="text"
        onChange={this.handleChange}
        name="change"
        value={this.state.change}
      />
    );
  }
}

The best way to bind event handlers in React, Binding event handlers in React can be tricky (you have JavaScript to thank for that). The component will render to update the name part. Calling render() will not generate a new handler for onClick , so the <butt on> setState({ [name]: event.target.value }); } render() { return ( <input onChange={this. There are couple of ways to pass parameter in event handlers, some are following. You can use an arrow function to wrap around an event handler and pass parameters: <button onClick={() => this.handleClick(id)} /> above example is equivalent to calling .bind or you can explicitly call bind. <button onClick={this.handleClick.bind(this, id)} />


Choosing the Best Approach for React Event Handlers, But passing an object's method as an event handler runs into JavaScript's When you want to tell a React component how to respond to an event, you pass a One solution is to use Function.prototype.bind() to set the value of this at the time of construction: Note that we are no longer passing the this. The most straightforward way to call a function is to call it directly: #!javascript var func = function () { // }; func () Calling the function this way will set its context ( this) to a global variable of an environment on which your JavaScript operates. In browsers it is a window global variable.


A New Way to Handle Events in React, *“Property Initializer Syntax”* sounds more fancy than it really is. the component, the “official” convention is to bind all the event handlers all the You can pass arguments without using bind in your render methods, or your  React events are named using camelCase, rather than lowercase. With JSX you pass a function as the event handler, rather than a string. For example, the HTML: <button onclick="activateLasers ()"> Activate Lasers </button>. is slightly different in React: <button onClick={activateLasers}> Activate Lasers </button>.


Event Handlers in React - JavaScript In Plain English, Working of React Event handlers is very similar to how handling of In case of React(/JSX), rather than passing a string, we pass a function as the event handler​. 'this' keyword is not defined by default in class components. In this, we will call .bind(this) in the render() function. More From Medium  If we need to pass custom parameters, then we can simply pass the parameters to the bind call. The SyntheticEvent will be passed as second parameter to the handler.