3 ms·
> you should just be able to do deleteItem={() => this.deleteItem(key)} Don’t do this. Arrow functions (and bind) are reallocated on every render, so this can
by rvanmil 8y ago
> you should just be able to do deleteItem={() => this.deleteItem(key)}
Don’t do this. Arrow functions (and bind) are reallocated on every render, so this can result in a lot of useless re-renders.
- yunyu 8y agoI think you meant allocations instead of rerenders - if you wanted to reduce rerenders, switching to PureComponent would be the way to go. IMO, what you're suggesting is a premature optimization.
- cygned 8y agoAn arrow function as a prop is a new function instance on every render causing child components that extend React.PureComponent to render even if no other property has changed. I consider this a code smell (b/c we had huge problems with it) and I usually give the advice to do it differently. There are exceptions, of course.
- yunyu 8y agoFair enough. In this case, I guess it's a tradeoff between code organization (should the child component be concerned with its position in the parent) versus avoiding rerenders.
- always_good 8y agoI don't think it's a concerns issue. You can simply decide to never create functions in any render(). There's even an eslint rule for it.
- yunyu 8y agoThe rationale behind that is avoiding re-renders, which can (but doesn't always) improve performance (shouldComponentUpdate can be slower than simply always re-rendering, per a React core developer): https://news.ycombinator.com/item?id=14418576 https://news.ycombinator.com/item?id=14418576 If you're concerned about allocation, here's what the same core developer has to say about inline functions in render(): https://twitter.com/sophiebits/status/938075351414063104?lang=en https://twitter.com/sophiebits/status/938075351414063104?lan... Also see the article that acemarke linked above. This is a textbook case of premature optimization. Why make your code harder to read just to achieve some performance gains that likely aren't even noticeable? Lastly, regarding the ESLint rule, sophiebits put it better than I can: I don’t recall ever having seen a credible-looking study about this, including in 2015.
- acemarke 8y agoThat only matters if the child components are actively attempting to optimize themselves by implementing `shouldComponentUpdate` with a shallow equality check (or are PureComponents, which do the same thing). Please see this post for clarification on the actual pros and cons of creating functions in `render`: https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578 https://cdb.reacttraining.com/react-inline-functions-and-per...