Are Lambda in JSX Attributes an anti-pattern?

前端 未结 3 534
刺人心
刺人心 2021-01-31 15:31

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

3条回答
  •  悲哀的现实
    2021-01-31 16:26

    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.

提交回复
热议问题