4 ms·
Just use arrow functions for your callbacks! This is trivial. Don't create a problem that doesn't exist.
by digitaLandscape 8y ago
Just use arrow functions for your callbacks!
This is trivial. Don't create a problem that doesn't exist.
- sdegutis 8y agoThis results in extra renders for an entire component chain, because comparing two arrow functions will always be different whereas comparing two pre-defined functions will always be the same. Hence React's recommendation to use 'bind'.
- gear54rus 8y agoWhat I don't get is why the React guys don't just call the passed functions with 'this' being the component, which seems like the most common use case. If you need to override this, you could indeed use bind (it's not overridable after that AFAIK so no logic is required from React side).
- sdegutis 8y agoThat's a good question, I never thought of that. Maybe while rendering they don't have easy access to which component is "this" due to the recursive algorithm they probably use? That's my only guess.
- acemarke 8y agoBecause it's really _not_ "the most common use case". Components often pass down callbacks through multiple levels of children. A basic example would be a Form component that renders something like: <Button onClick={this.onFirstNameChanged} /> The proper context for `this` is the Form, but the callback is used in the context of the Button. Besides, one of the main tenets of React is that "it's just JS", so normal JS rules apply. Now, the old-style `React.createClass()` method _did_ actually bind all "class methods" to the component instances so you didn't have to worry about it, but that wasn't typical JS behavior. ES6 classes don't auto-bind their methods, so neither does the `React.Component` base class. The current recommended approach is to use the Stage 3 Class Properties syntax, which allows defining class methods as arrow functions that are auto-bound to the proper class/component instance. Very long-term, the React team intends to introduce a "stateful functional component" API that doesn't have to worry about class instances, but that's going to be a while. (There are some assorted userland experiments with writing "`this`-less components" as well.)
- acemarke 8y agoNo, that's only true _if_ a child component is explicitly attempting to optimize its performance by doing shallow equality checks on its props in `shouldComponentUpdate` (or is a `PureComponent`, which does the same thing automatically). Otherwise, React's default behavior is to re-render a component tree all the way down anyway, so it doesn't matter whether a given prop has actually changed its reference or not. See this post by Ryan Florence that explains why "arrow functions in render" is not a big deal: https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578 https://cdb.reacttraining.com/react-inline-functions-and-per...