Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Memoize getEntityRecords to prevent infinite re-renders #26447

Merged
merged 7 commits into from
Nov 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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