ElMuchacho
ElMuchacho

Reputation: 300

Event handling in react: in which cases do we need to use arrow function on event, and when do we just need to pass class method(function)?

Example:

1)

<button onClick="{this.handleClick}">
 Click me
</button>
<button onClick={() => this.handleClick()}>

Why right here we can't just pass a function? I mean WHY do we need here an arrow function.

import React, { useState } from "react";

function Example() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>you clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>click me</button>
    </div>
  );
}

Upvotes: 1

Views: 1338

Answers (2)

Dhara Vihol
Dhara Vihol

Reputation: 612

You can use arrow function when you want to pass parameter to an event handler. Using arrow function is a choice, not necessity.

Syntax:

<button onClick={() => this.handleClick(id)} />

When you do not want to pass any parameter, you can pass reference of the function.

<button onClick={this.handleClick}>Click Me</button>

Important:

Writing an arrow function means binding any function in render time.

<button onClick={this.handleClick.bind(this, id)} />

Arrow function is alternative of above syntax. So, You can choose to use arrow function. The difference is, Binding a function in render creates a new function each time the component renders. That means,, using arrow function or binding a function in render time can create performance issue in your application.

Follow this documentation for more details: https://reactjs.org/docs/faq-functions.html

Upvotes: 2

Dani
Dani

Reputation: 584

If you don't use an arrow function that function will get executed on render() regardless of a button click. That's why you set an arrow function, to prevent that behavior. In your case on every render, the counter will increase if you don't use the arrow function syntax

Upvotes: 4

Related Questions