Skip to content

Commit

Permalink
Data: Avoid calling listeners on unchanging state (#5339)
Browse files Browse the repository at this point in the history
  • Loading branch information
aduth authored Mar 5, 2018
1 parent 979904e commit c8e1444
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
14 changes: 13 additions & 1 deletion data/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,19 @@ export function registerReducer( reducerKey, reducer ) {
}
const store = createStore( reducer, flowRight( enhancers ) );
stores[ reducerKey ] = store;
store.subscribe( globalListener );

// Customize subscribe behavior to call listeners only on effective change,
// not on every dispatch.
let lastState = store.getState();
store.subscribe( () => {
const state = store.getState();
const hasChanged = state !== lastState;
lastState = state;

if ( hasChanged ) {
globalListener();
}
} );

return store;
}
Expand Down
30 changes: 30 additions & 0 deletions data/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,26 @@ describe( 'withSelect', () => {

store.dispatch( { type: 'increment' } );
} );

itWithExtraAssertions( 'should not rerun selection on unchanging state', () => {
const store = registerReducer( 'unchanging', ( state = {} ) => state );

registerSelectors( 'unchanging', {
getState: ( state ) => state,
} );

const mapSelectToProps = jest.fn();

const Component = compose( [
withSelectImplementation( mapSelectToProps ),
] )( () => <div /> );

wrapper = mount( <Component /> );

store.dispatch( { type: 'dummy' } );

expect( mapSelectToProps ).toHaveBeenCalledTimes( 1 );
} );
}

cases( withSelect );
Expand Down Expand Up @@ -380,6 +400,16 @@ describe( 'subscribe', () => {

expect( secondListener ).toHaveBeenCalled();
} );

it( 'does not call listeners if state has not changed', () => {
const store = registerReducer( 'unchanging', ( state = {} ) => state );
const listener = jest.fn();
subscribeWithUnsubscribe( listener );

store.dispatch( { type: 'dummy' } );

expect( listener ).not.toHaveBeenCalled();
} );
} );

describe( 'dispatch', () => {
Expand Down

0 comments on commit c8e1444

Please sign in to comment.