Skip to content

Commit

Permalink
Memoize getEntityRecords to prevent infinite re-renders (#26447)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin940726 authored Nov 3, 2020
1 parent fd1fc60 commit 259751d
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 2 deletions.
13 changes: 12 additions & 1 deletion packages/core-data/src/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@ import { getQueriedItems } from './queried-data';
import { DEFAULT_ENTITY_KEY } from './entities';
import { getNormalizedCommaSeparable } from './utils';

/**
* Shared reference to an empty array for cases where it is important to avoid
* returning a new array reference on every invocation, as in a connected or
* other pure component which performs `shouldComponentUpdate` check on props.
* This should be used as a last resort, since the normalized data should be
* maintained by the reducer result in state.
*
* @type {Array}
*/
const EMPTY_ARRAY = [];

/**
* Returns true if a request is in progress for embed preview data, or false
* otherwise.
Expand Down Expand Up @@ -238,7 +249,7 @@ export function getEntityRecords( state, kind, name, query ) {
'queriedData',
] );
if ( ! queriedState ) {
return [];
return EMPTY_ARRAY;
}
return getQueriedItems( queriedState, query );
}
Expand Down
36 changes: 36 additions & 0 deletions packages/core-data/src/test/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,42 @@ describe( 'getEntityRecords', () => {
{ slug: 'page' },
] );
} );

it( 'should return the same instance with the same arguments', () => {
let state = deepFreeze( {
entities: {
data: {},
},
} );

const postTypeFirstRecords = getEntityRecords(
state,
'root',
'postType'
);
const wpBlockFirstRecords = getEntityRecords(
state,
'postType',
'wp_block'
);

// Simulate update states
state = { ...state };

const postTypeSecondRecords = getEntityRecords(
state,
'root',
'postType'
);
const wpBlockSecondRecords = getEntityRecords(
state,
'postType',
'wp_block'
);

expect( postTypeFirstRecords ).toBe( postTypeSecondRecords );
expect( wpBlockFirstRecords ).toBe( wpBlockSecondRecords );
} );
} );

describe( '__experimentalGetDirtyEntityRecords', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ export default function WidgetAreasBlockEditorProvider( {
'postType',
'wp_block'
),
} )
} ),
[]
);
const { setIsInserterOpened } = useDispatch( 'core/edit-widgets' );

Expand Down

0 comments on commit 259751d

Please sign in to comment.