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?

7
  • 2
    {} => true si not valid. And what is the purpose of having a function that always returns true ? Commented Apr 25, 2018 at 9: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 Commented Apr 25, 2018 at 9:23
  • @klugjo thanks have corrected, purpose is not what’s in the function, rather how the function is defined. Commented Apr 25, 2018 at 9:24
  • @JonasW. Why do I care: simply curiosity Commented Apr 25, 2018 at 9:26
  • 1
    AFAIK, render = () => {} won't work, will it? Like a half year ago I tried it and it generated an error in babel Commented Apr 25, 2018 at 9:26

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I didn’t even think of that point, wouldn’t it cause large performance issues if this is happening?
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
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.