Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5ffc169

Browse files
mfunkiegaearon
authored andcommitted
Update ES6 class documentation with binding perf
Adding a note in the ES6 class documentation about function binding. Recommending that you bind your handlers in the constructor so that they are referentially the same function every time render is invoked (helps with child components that might potentially call shouldComponentUpdate)
1 parent 1aa2064 commit 5ffc169

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

docs/docs/05-reusable-components.md

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,13 +205,14 @@ export class Counter extends React.Component {
205205
constructor(props) {
206206
super(props);
207207
this.state = {count: props.initialCount};
208+
this.tick = this.tick.bind(this);
208209
}
209210
tick() {
210211
this.setState({count: this.state.count + 1});
211212
}
212213
render() {
213214
return (
214-
<div onClick={this.tick.bind(this)}>
215+
<div onClick={this.tick}>
215216
Clicks: {this.state.count}
216217
</div>
217218
);
@@ -223,7 +224,34 @@ Counter.defaultProps = { initialCount: 0 };
223224

224225
### No Autobinding
225226

226-
Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind `this` to the instance. You'll have to explicitly use `.bind(this)` or [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) `=>`.
227+
Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind `this` to the instance. You'll have to explicitly use `.bind(this)` or [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) `=>`:
228+
229+
```javascript
230+
// You can use bind() to preserve `this`
231+
<div onClick={this.tick.bind(this)}>
232+
233+
// Or you can use arrow functions
234+
<div onClick={() => this.tick()}>
235+
```
236+
237+
We recommend that you bind your event handlers in the constructor so they are only bound once for every instance:
238+
239+
```javascript
240+
constructor(props) {
241+
super(props);
242+
this.state = {count: props.initialCount};
243+
this.tick = this.tick.bind(this);
244+
}
245+
```
246+
247+
Now you can use `this.tick` directly as it was bound once in the constructor:
248+
249+
```javascript
250+
// It is already bound in the constructor
251+
<div onClick={this.tick}>
252+
```
253+
254+
This is better for performance of your application, especially if you implement [shouldComponentUpdate()](/react/docs/component-specs.html#updating-shouldcomponentupdate) with a [shallow comparison](/react/docs/shallow-compare.html) in the child components.
227255

228256
### No Mixins
229257

0 commit comments

Comments
 (0)