Ending the debate on inline functions in React – Flexport Engineering

Ending the debate on inline functions in React  #reactjs

  • In the example above, this.props.onAlert in the callback has the correct reference to this.Why do other people dislike inline functions?An inline function in render allocates a new function instance each time render is called.
  • However, in Flexport’s React app, the garbage collector penalty is dwarfed by another performance issue caused by inline functions: wasteful re-rendering of pure components.Recall from Part 1 of this blog series that pure components rely on a shallow equality comparison in shouldComponentUpdate to determine if any props or state have…
  • Since two different function instances are never equal, inline functions will cause the shallow equality comparison to fail, and thus will always trigger a re-render.
  • So as a React developer, what in the world are you supposed to do?reflective-bind to the rescueThe answer: freely use inline arrow functions in render, and use our ✨new✨ reflective-bind Babel transform to eliminate wasteful re-renders with almost no code change.Total internal reflection.
  • To do that, the Babel plugin hoists the arrow function to the top level, and replaces it with a call to reflectiveBind, passing in the hoisted function and the closed over variables as arguments:With these transforms in place, we can use reflectiveEqual in our shouldComponentUpdate to check for function equality.Performance…

Using inline functions in React is convenient but can be contentious because of their perceived impact on performance. Today Flexport is introducing our solution to the debate: a Babel transform…
Continue reading “Ending the debate on inline functions in React – Flexport Engineering”