Skip to content

Commit

Permalink
Memoize mapState
Browse files Browse the repository at this point in the history
mapState can be memoized automatically when it does not take the second
parameter.

I had to change invocationCount assert to 1 from 2. I'm pretty sure it
should be invoked only once on the initial render and not on prop
changes again.
  • Loading branch information
esamattis committed Sep 9, 2015
1 parent 922fedc commit 8f5f825
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
19 changes: 17 additions & 2 deletions src/components/createConnect.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ export default function createConnect(React) {
super(props, context);
this.version = version;
this.store = props.store || context.store;
this.mapStateMemoize = null;

invariant(this.store,
`Could not find "store" in either the context or ` +
Expand Down Expand Up @@ -157,6 +158,9 @@ export default function createConnect(React) {
this.updateDispatchProps(nextProps);
}

if (shouldUpdateStateProps) {
this.mapStateMemoize = null;
}
}
}

Expand All @@ -169,7 +173,12 @@ export default function createConnect(React) {
return;
}

this.setState({storeState: this.store.getState()});
const storeState = this.store.getState();
if (storeState !== this.state.storeState) {
this.mapStateMemoize = null;
}

this.setState({storeState});
}

getWrappedInstance() {
Expand All @@ -181,8 +190,12 @@ export default function createConnect(React) {
}

computeNextState() {
if (this.mapStateMemoize === null) {
this.mapStateMemoize = computeStateProps(this.state.storeState, this.props);
}

return computeNextState(
computeStateProps(this.state.storeState, this.props),
this.mapStateMemoize,
this.state.dispatchProps,
this.props
);
Expand Down Expand Up @@ -214,6 +227,8 @@ export default function createConnect(React) {
// We are hot reloading!
this.version = version;

this.mapStateMemoize = null;

// Update the state and bindings.
this.trySubscribe();
this.updateDispatchProps();
Expand Down
2 changes: 1 addition & 1 deletion test/components/connect.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ describe('React', () => {
outerComponent.setFoo('BAR');
outerComponent.setFoo('DID');

expect(invocationCount).toEqual(2);
expect(invocationCount).toEqual(1);
});

it('should invoke mapState every time props are changed if it has a second argument', () => {
Expand Down

0 comments on commit 8f5f825

Please sign in to comment.