Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

reactjs - Are Lambda in JSX Attributes an anti-pattern?

I started using a new linter today (tslint-react) and it is giving me the following warning:

"Lambdas are forbidden in JSX attributes due to their rendering performance impact"

I get that this causes the a new function to be created with each render. And that it could trigger unneeded re-renders because the child component will think it's props have changed.

But my question is this, how else can one pass parameters to an event handler inside a loop:

customers.map( c => <Btn onClick={ () => this.deleteCust(c.id) } /> );
question from:https://stackoverflow.com/questions/43968779/are-lambda-in-jsx-attributes-an-anti-pattern

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Definitely not an antipattern.

Lambdas (arrow functions) have no impact on rendering performance.

The only thing that has an impact is the implementation of shouldComponentUpdate. This function returns true by default, meaning that the component is always rendered. That means that even if the props don't change, the component is still rendered again. And that's the default behavior.

Changing arrow function to a bound method won't improve the performance if you don't implement shouldComponentUpdate.

It's true that not using arrow functions can simplify the implementation of shouldComponentUpdate and they should not be used with PureComponent but they are not an antipattern. They can simplify many patterns, e.g. when adding an additional parameter to function (e.g. what you are doing in your example).

Also note that React has stateless components which cannot even implement shouldComponentUpdate and therefore they are always rendered.

Don't think about performance impact until you actually find a performance problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...