React Native Info

Home Awsomeness Contact

🌶 Should I Use Inline Function in Render()

Short answer is “better not”. The reasons are as below.

Concern in Rendering Performance

As suggested by React official doc

Using an arrow function in render creates a new function each time the component renders, which may break optimizations based on strict identity comparison.

Is it OK to use arrow functions in render methods?

Generally speaking, yes, it is OK, and it is often the easiest way to pass parameters to callback functions. If you do have performance issues, by all means, optimize!

In another word, it is OK to add sugar to Coffee. But be mindful that sugar is not good for you.

Using inline function in render() does not have direct impact on rendering performance. What it compromises is the expectation of PureComponent which is the first-in-mind option whenever an optimisation is wanted.

More specifically, inline function creates a new reference of the function for each render pass. When such reference is passed down as a prop to a PureComponent, it gives false of the shallow props comparison all time and force render the subtree rooted by the PureComponent.

Moreover, the above issue could be obscured when the PureComponent is wrapped within layers of HOCs, which renders a false positive optimisation a very easy miss.

Concern in Memory Consumption

Another concern is, again, inline function creates a new function for each render pass, which puts more burden to the runtime GC. This penalty is minor compared to the rendering performance issue above.

Wrap Up, Reevaluate the Trade-Off

We sometimes trade off complexity and code readability for performance. This is because of hardware limitation. Sometimes we go too far hence the word “premature optimisation” becomes prevailing. But we also need to be mindful when such trade-off falls short, and when “premature optimisation” is over used. In the end of the day, it is the mindfull, relentless optimisations, small and big alike, that make underpinnings of the industry such as operating systems, browser, network, AI, etc., faster and faster iteration by iteration, and make computer science computer science, an interesting field to stay.

…by all means, optimize!

For that matter, avoiding inline function in render() gives small performance gains at a cost that is comparablely small. On the other hand, the convenience gained by inline function is rather questionable. For example, when the function grows, it will find itself inconvenient and untestable sitting in render(), which marks a noticeable contradiction and suggests the opposite practice.

Good development culture should not be stringent. Nonetheless, it should in its best effort facilitate consistency, focus on performance, and call out suboptimal practices based on reasoning, such as, “sugar is not good for you, because it is one of the greatest threats to cardiovascular disease”.

, , , , ,