5

Edit: Specifically, does the AirBnb example below have some nuance that exempts it from the tslint rule/ SO thread in the comment by Ori Drori?

I'm using tslint-react and also following AirBnb's React style guide

AirBnb's rule "Use arrow functions to close over local variables" shows a lambda function being used in the return (render) of a pure stateless component.

function ItemList(props) {
  return (
    <ul>
      {props.items.map((item, index) => (
        <Item
          key={item.key}
          onClick={() => doSomethingWith(item.name, index)} // This ok??
        />
      ))}
    </ul>
  );
}

tslint-react's rule "jsx-no-lambda" seems to say this is a bad thing.

jsx-no-lambda: Creating new anonymous functions (with either the function syntax or ES2015 arrow syntax) inside the render call stack works against pure component rendering. When doing an equality check between two lambdas, React will always consider them unequal values and force the component to re-render more often than necessary.

I'm confused as to the best practice here, and whether AirBnb's style guide has a nuance that exempts it from concern.

Cheers!

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Tyler
  • 1,705
  • 2
  • 18
  • 26
  • 2
    This isn't a duplicate! @Tyler isn't asking why its a bad practice? The question deals with the seemingly contradicting rules. – Jikku Jose Jun 29 '17 at 18:34
  • 2
    @JikkuJose: Agreed. I'm voting to re-open. – hippietrail Sep 23 '17 at 02:09
  • After working with React for awhile now, I think I can safely say that there was (is?) no nuance to the AirBnb example that exempts it from the `jsx-no-lambda` rule. I think they just did it that way for brevity in describing an unrelated concept. I still am surprised it was closed. – Tyler Oct 04 '17 at 15:56
  • @Tyler I'd say that the point of not using lambda is for `onClick` kind of calls (or any function that is passed as a prop to child components), because every re-render of the "parent" component will create a new function which will trigger a possibly unnecessary rerender of the child components. For example: ` this.props.handleClick(this.props.id)} id={this.props.id} />` would trigger a rerender of the `ComponentName` component every time the parent component rerenders, even if the `id` prop is not changed at all. Id be happy to elaborate more about this if needed – Sergio Moura Oct 16 '18 at 19:43

0 Answers0