From fb13cf55feb3391af30fb8c9e45b6c2aec40c6ae Mon Sep 17 00:00:00 2001 From: Mark Funk Date: Tue, 29 Mar 2016 10:38:34 -0700 Subject: [PATCH] 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) --- docs/docs/05-reusable-components.md | 32 +++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/docs/docs/05-reusable-components.md b/docs/docs/05-reusable-components.md index b79e329e5a..64fcf75cdd 100644 --- a/docs/docs/05-reusable-components.md +++ b/docs/docs/05-reusable-components.md @@ -205,13 +205,14 @@ export class Counter extends React.Component { constructor(props) { super(props); this.state = {count: props.initialCount}; + this.tick = this.tick.bind(this); } tick() { this.setState({count: this.state.count + 1}); } render() { return ( -
+
Clicks: {this.state.count}
); @@ -223,7 +224,34 @@ Counter.defaultProps = { initialCount: 0 }; ### No Autobinding -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) `=>`. +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) `=>`: + +```javascript +// You can use bind() to preserve `this` +
+ +// Or you can use arrow functions +
this.tick()}> +``` + +We recommend that you bind your event handlers in the constructor so they are only bound once for every instance: + +```javascript +constructor(props) { + super(props); + this.state = {count: props.initialCount}; + this.tick = this.tick.bind(this); +} +``` + +Now you can use `this.tick` directly as it was bound once in the constructor: + +```javascript +// It is already bound in the constructor +
+``` + +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. ### No Mixins