binding event handlers in react boilerplate

42 views Asked by At

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?

1

There are 1 answers

2
Lakshya Thakur On

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.