Are Lambda in JSX attributes anti-pattern?

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

"Lambdas are not allowed in JSX attributes due to rendering performance impact"

I understand that this leads to the creation of a new function with each rendering. And this can cause unnecessary re-rendering, because the child component will think that the details have changed.

But my question is how else can I pass parameters to the event handler inside the loop:

customers.map( c => <Btn onClick={ () => this.deleteCust(c.id) } /> );
+32
source share
3 answers

Definitely not an antipattern.

Lambdas (arrow functions) do not affect rendering performance.

, , shouldComponentUpdate. true , , . , , . .

, shouldComponentUpdate.

, shouldComponentUpdate, PureComponent, . , . (, ).

, React , shouldComponentUpdate, .

, .

+52

, / , ; Javascript ,

function mapCustomersToButton(c) {
  function handleBtnClick() {
    this.deleteCust(c.id);
  }

  return <Btn onClick={handleBtnClick} />
}

return customers.map(mapCustomersToButton);

handleBtnClick c, mapCustomersToButton; .

:

return customers.map(c => <Btn onClick={() => this.deleteCust(c.id)} />);
0

, , , React.PureComponent useMemo. (Lambda) prop ( JSX), , JS . , , JavaScript .

, . :

#1 Lamba approach
customers.map( c => <Btn onClick={ () => this.deleteCust(c.id) } /> );

#2 bind apprach
customers.map( c => <Btn onClick={ this.deleteCust.bind(this, c.id) } /> );

#3 call approach
customers.map( c => <Btn onClick={ this.deleteCust.call(this, c.id) } /> );

#4 apply approach
customers.map( c => <Btn onClick={ this.deleteCust.apply(this, [c.id]) } /> );

, . :

const Btn = ({ clicked, customer }) => {
  const buttonClickHandler = () => {
    clicked(customer.id)
  }
  return <button onClick={buttonClickHandler}>Click me!</button> 
}

const App = () => {
  return (
    <App>
      { customers.map(c => <Btn customer={c} clicked={deleteCust} />) }
    </App>
  )
}

So now, because instead of using an anonymous function (which cannot be reused), we use a function expression in a constant, React does not recreate a new function every time a new component is rendered, and the garbage collector can be collected in parts!

0
source

Source: https://habr.com/ru/post/1677128/


All Articles