0

There are 4 methods for binding event handlers that i know. The first one is by binding within the DOM element in render():

<button onClick = {this.clickHandler.bind(this)}>Event</button>

The second one is using an arrow function within the DOM element in render():

<button onClick = {() => this.clickHandler()}>Event</button>

The third one is by binding within the class constuctor:

constructor(props) {
        super(props)
        this.state = {
             message: "Click"
        }
        **this.clickHandler = this.clickHandler.bind(this);**
    }
render() {
        return (
            <div>
                <div>{this.state.message}</div>
                **<button onClick = {this.clickHandler}>Event</button>**
            </div>
        )
    }

The forth way is by changing the class property to an arrow function:

clickHandler = () => {
        this.setState({
            message: 'Goodbye!'
        })
    }

So which way is best?

Mavrickj9
  • 25
  • 9

1 Answers1

1

From what I know :-

  • In 1st case, a newly bound clickHandler will be created on every render of your React app.
  • In 2nd case, a new anonymous arrow function will be created which internally calls the clickHandler (on-execution) on every render of your React app.
  • Both 3rd and 4th are better since they cause one-time creation of the clickHandler. They are outside the render flow.
Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
  • Which between 3rd and 4th would you say is fastest on compilation and execution? – Mavrickj9 Mar 23 '21 at 15:04
  • That really boils down to arrow function vs regular function performance. I haven’t explored that. I think arrow function is what I would like to go with since I am even skipping the creation of one-time bound function. But not really sure how much of a performance gain would that be. – Lakshya Thakur Mar 23 '21 at 15:19