0

Apart from needing to create a new function each time render is invoked, are there any other differences from using:

class {
   on = () => true
   render = () => <z on={this.on} />
}

vs

class {
   render = () => <z on={() => true} />
}

For example, are there any optimizations that browsers make? Are there any implementation differences?

If there are zero differences, would it make sense for something like bable to transform the code to avoid creating the function in the render function?

FabianCook
  • 20,269
  • 16
  • 67
  • 115
  • 2
    `{} => true` si not valid. And what is the purpose of having a function that always returns true ? – klugjo Apr 25 '18 at 09:21
  • As always: yes the second *might* be faster if optimizations in js would be logical. And even then: Why do you care? Are you having performance problems? If so, its definetly not the arrow func – Jonas Wilms Apr 25 '18 at 09:23
  • @klugjo thanks have corrected, purpose is not what’s in the function, rather how the function is defined. – FabianCook Apr 25 '18 at 09:24
  • @JonasW. Why do I care: simply curiosity – FabianCook Apr 25 '18 at 09:26
  • 1
    AFAIK, ```render = () => {}``` won't work, will it? Like a half year ago I tried it and it generated an error in babel – Limbo Apr 25 '18 at 09:26
  • I guess I’m asking what’s the difference between these two except for one is creating a new function https://codesandbox.io/s/7jo85xpx2x – FabianCook Apr 25 '18 at 09:35
  • @FabianCook, there isn't any difference between the two apart from the fact that a new function is created on every render, You can check https://stackoverflow.com/questions/45053622/how-to-avoid-binding-in-render-method/45053753#45053753 is you are looking for ways to avoid arrow function in render – Shubham Khatri Apr 25 '18 at 11:00

1 Answers1

1

From Reactjs point of view, since the arrow function creates a new function everytime, it could potentially cause two performance related problems:

  • Could invoke the garbage collector more frequently than usual
  • Will cause unnecessary re-render of your components(even the pure components) as new function will be considered as a new prop.

There is already a babel plugin that solves this re-render problem caused by using arrow fn: reflective-bind The performance benefit from using this plugin has been described here

Anu
  • 1,079
  • 8
  • 12
  • I didn’t even think of that point, wouldn’t it cause large performance issues if this is happening? – FabianCook Apr 25 '18 at 09:37
  • 1
    Well that depends on many factors like how many arrow fn you are passing as props, how many levels of component nesting to which these arrow fns are passed as props etc – Anu Apr 25 '18 at 09:46
  • @FabianCook Do let me know if you have any more questions. If the answer helped you, please accept it so that it will help others in the future. – Anu May 09 '18 at 08:05