Home > Blockchain >  "onClose={handleClose}" better then "onClose={() => handleClose}" function sy
"onClose={handleClose}" better then "onClose={() => handleClose}" function sy

Time:12-16

I heard somewhere that

onClose={handleClose}

syntax is better than

onClose={() => handleClose} 

Because the function is not created every time in render or something like that, and it's better for performance in general.

I tried to find information about this on the Internet, but did't find the desired result. I'm interested in the difference in writing syntax in terms of architecture design, which is better computed. Can someone tell me the answer to my question?

CodePudding user response:

Imagine, that you have a few same functionality buttons in one component which are "Close" and "Cancel":

Example here

If you use this approach:

<button onClick={() => onClose()}>Close</button>
...some code...
<button onClick={() => onClose()}>Cancel</button>

It will create two anonymous functions that will be stored separately in memory. This will not have the best effect on performance.

But in this case:

<button onClick={onClose}>Close</button>
...some code...
<button onClick={onClose}>Cancel</button>

You will use just one function, without unnecessary memory filling.

CodePudding user response:

It will create 2 new functions on each render, that's true.

But this is how React works, it is doing it every time when something re-renders. You can not prevent that. Each function created inside a component changes its reference on each render.

<button onClose={handleClose}>Cancel</button>

this will be better, but keep in mind, that onClick passes the Event to that function. If you decide one day to add an argument to it, you have to change every place from onClose={handleClose} to onClose={() => handleClose(...)}, even if you don't pass and property, because otherwise it will pass an Event to it and this may lead to bugs

  • Related