Skip to content

Commit ebe63e4

Browse files
committed
Memoize mapState
mapState can be memoized automatically when it does not take the second parameter.
1 parent 922fedc commit ebe63e4

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

src/components/createConnect.js

+17-2
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ export default function createConnect(React) {
108108
super(props, context);
109109
this.version = version;
110110
this.store = props.store || context.store;
111+
this.mapStateMemoize = null;
111112

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

161+
if (shouldUpdateStateProps) {
162+
this.mapStateMemoize = null;
163+
}
160164
}
161165
}
162166

@@ -169,7 +173,12 @@ export default function createConnect(React) {
169173
return;
170174
}
171175

172-
this.setState({storeState: this.store.getState()});
176+
const storeState = this.store.getState();
177+
if (storeState !== this.state.storeState) {
178+
this.mapStateMemoize = null;
179+
}
180+
181+
this.setState({storeState});
173182
}
174183

175184
getWrappedInstance() {
@@ -181,8 +190,12 @@ export default function createConnect(React) {
181190
}
182191

183192
computeNextState() {
193+
if (this.mapStateMemoize === null) {
194+
this.mapStateMemoize = computeStateProps(this.state.storeState, this.props);
195+
}
196+
184197
return computeNextState(
185-
computeStateProps(this.state.storeState, this.props),
198+
this.mapStateMemoize,
186199
this.state.dispatchProps,
187200
this.props
188201
);
@@ -214,6 +227,8 @@ export default function createConnect(React) {
214227
// We are hot reloading!
215228
this.version = version;
216229

230+
this.mapStateMemoize = null;
231+
217232
// Update the state and bindings.
218233
this.trySubscribe();
219234
this.updateDispatchProps();

test/components/connect.spec.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,7 @@ describe('React', () => {
441441
outerComponent.setFoo('BAR');
442442
outerComponent.setFoo('DID');
443443

444-
expect(invocationCount).toEqual(2);
444+
expect(invocationCount).toEqual(1);
445445
});
446446

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

0 commit comments

Comments
 (0)