Skip to content

Commit

Permalink
Cache Default Props
Browse files Browse the repository at this point in the history
The `getDefaultProps` return value should not be dependent on any external data (including `this.props` and `this.state`), so the return value should be consistent everytime we call it.

This caches the return value so we do not do work and allocate memory unnecessarily.
  • Loading branch information
jeffmo authored and zpao committed Jun 26, 2013
1 parent 6f04bd9 commit 4393045
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions src/core/ReactCompositeComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,8 @@ var ReactCompositeComponentInterface = {
// ==== Definition methods ====

/**
* Invoked when the component is mounted and whenever new props are received.
* Values in the returned mapping will be set on `this.props` if that prop is
* not specified (i.e. using an `in` check).
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
Expand Down Expand Up @@ -504,6 +503,8 @@ var ReactCompositeComponentMixin = {
mountComponent: function(rootID, transaction) {
ReactComponent.Mixin.mountComponent.call(this, rootID, transaction);
this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING;

this._defaultProps = this.getDefaultProps ? this.getDefaultProps() : null;
this._processProps(this.props);

if (this.__reactAutoBindMap) {
Expand Down Expand Up @@ -549,6 +550,8 @@ var ReactCompositeComponentMixin = {
}
this._compositeLifeCycleState = null;

this._defaultProps = null;

ReactComponent.Mixin.unmountComponent.call(this);
this._renderedComponent.unmountComponent();
this._renderedComponent = null;
Expand Down Expand Up @@ -651,12 +654,10 @@ var ReactCompositeComponentMixin = {
*/
_processProps: function(props) {
var propName;
if (this.getDefaultProps) {
var defaultProps = this.getDefaultProps();
for (propName in defaultProps) {
if (!(propName in props)) {
props[propName] = defaultProps[propName];
}
var defaultProps = this._defaultProps;
for (propName in defaultProps) {
if (!(propName in props)) {
props[propName] = defaultProps[propName];
}
}
var propDeclarations = this.constructor.propDeclarations;
Expand Down

0 comments on commit 4393045

Please sign in to comment.