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
Well as far as I know, it has an impact on performance even if you're not using React.PureComponent
or useMemo
. When you define anonymous arrow function (Lambda) in component's prop (JSX attribute), the same function is created on each render so that JS engine can't reuse it. That recreation slows don't performance because JavaScript's engine garbage collector has to collect those unneccessary functions.
There are several other approaches which behaves the same. Take a look at example below:
#1 Lamba approach
customers.map( c => this.deleteCust(c.id) } /> );
#2 bind apprach
customers.map( c => );
#3 call approach
customers.map( c => );
#4 apply approach
customers.map( c => );
I would say the recommended approach is to create a separate function inside the component being mapped. Let's modify a bit your example:
const Btn = ({ clicked, customer }) => {
const buttonClickHandler = () => {
clicked(customer.id)
}
return
}
const App = () => {
return (
{ customers.map(c => ) }
)
}
So now, since instead of anonymous function (which can't be reused) we're using function expression in a constant, React doesn't recreate new function every new component re render and the garbage collector can rest in piece!