Skip to content

Commit be07f7a

Browse files
Ensiveljharb
authored andcommitted
[guide] [react] add more context about arrow functions, as props and in class fields
1 parent 495a62a commit be07f7a

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

react/README.md

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -531,7 +531,7 @@ We don’t recommend using indexes for keys if the order of items may change.
531531

532532
## Methods
533533

534-
- Use arrow functions to close over local variables.
534+
- Use arrow functions to close over local variables. It is handy when you need to pass additional data to an event handler. Although, make sure they [do not massively hurt performance](https://www.bignerdranch.com/blog/choosing-the-best-approach-for-react-event-handlers/), in particular when passed to custom components that might be PureComponents, because they will trigger a possibly needless rerender every time.
535535

536536
```jsx
537537
function ItemList(props) {
@@ -540,7 +540,7 @@ We don’t recommend using indexes for keys if the order of items may change.
540540
{props.items.map((item, index) => (
541541
<Item
542542
key={item.key}
543-
onClick={() => doSomethingWith(item.name, index)}
543+
onClick={(event) => doSomethingWith(event, item.name, index)}
544544
/>
545545
))}
546546
</ul>
@@ -550,7 +550,7 @@ We don’t recommend using indexes for keys if the order of items may change.
550550

551551
- Bind event handlers for the render method in the constructor. eslint: [`react/jsx-no-bind`](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md)
552552

553-
> Why? A bind call in the render path creates a brand new function on every single render.
553+
> Why? A bind call in the render path creates a brand new function on every single render. Do not use arrow functions in class fields, because it makes them [challenging to test and debug, and can negatively impact performance](https://medium.com/@charpeni/arrow-functions-in-class-properties-might-not-be-as-great-as-we-think-3b3551c440b1), and because conceptually, class fields are for data, not logic.
554554

555555
```jsx
556556
// bad
@@ -564,6 +564,17 @@ We don’t recommend using indexes for keys if the order of items may change.
564564
}
565565
}
566566
567+
// very bad
568+
class extends React.Component {
569+
onClickDiv = () => {
570+
// do stuff
571+
}
572+
573+
render() {
574+
return <div onClick={this.onClickDiv} />
575+
}
576+
}
577+
567578
// good
568579
class extends React.Component {
569580
constructor(props) {

0 commit comments

Comments
 (0)