0

I want to understand How the below code works and what is the difference between the two and how it gets rendered in react application

          <button
            className="btn btn-outline-danger"
            onClick={() => onTestClick(test)}>
            Test
          </button>


          <button
            className="btn btn-outline-danger"
            onClick={onTestClick(test)}>
            Test
          </button>
Ram Somani
  • 231
  • 3
  • 12
  • Does this answer your question? [When to call function vs function() in react onClick?](https://stackoverflow.com/questions/42178136/when-to-call-function-vs-function-in-react-onclick) – Hassan Imam Apr 10 '21 at 09:24
  • You can take a look at this too [Correct use of arrow functions in React](https://stackoverflow.com/questions/48699573/correct-use-of-arrow-functions-in-react) – Ravikumar Apr 10 '21 at 09:29

1 Answers1

0

To make it clear, this is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, such as onClick={this.handleClick}​, you should bind that method.

If calling bind annoys you, there are two ways you can get around this. If you are using the experimental public class fields syntax, you can use class fields to correctly bind callbacks.

If you aren’t using class fields syntax, you can use an arrow function in the callback.

The problem with arrow function syntax is that a different callback is created each time the button renders. In most cases, this is fine. However, 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.

You can read more about this on their documentation here:

https://reactjs.org/docs/handling-events.html

Blessing
  • 2,450
  • 15
  • 22