Skip to content

Commit

Permalink
Data: Include more details when shallow equality fails in 'useSelect' (
Browse files Browse the repository at this point in the history
…WordPress#67713)


Co-authored-by: Mamaduka <[email protected]>
Co-authored-by: jsnajdr <[email protected]>
Co-authored-by: tyxla <[email protected]>
  • Loading branch information
4 people authored and yogeshbhutkar committed Dec 18, 2024
1 parent e05ae64 commit 6ab4c36
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions packages/data/src/components/use-select/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,25 @@ import useAsyncMode from '../async-mode-provider/use-async-mode';

const renderQueue = createQueue();

function warnOnUnstableReference( a, b ) {
if ( ! a || ! b ) {
return;
}

const keys =
typeof a === 'object' && typeof b === 'object'
? Object.keys( a ).filter( ( k ) => a[ k ] !== b[ k ] )
: [];

// eslint-disable-next-line no-console
console.warn(
'The `useSelect` hook returns different values when called with the same state and parameters.\n' +
'This can lead to unnecessary re-renders and performance issues if not fixed.\n\n' +
'Non-equal value keys: %s\n\n',
keys.join( ', ' )
);
}

/**
* @typedef {import('../../types').StoreDescriptor<C>} StoreDescriptor
* @template {import('../../types').AnyConfig} C
Expand Down Expand Up @@ -159,10 +178,7 @@ function Store( registry, suspense ) {
if ( ! didWarnUnstableReference ) {
const secondMapResult = mapSelect( select, registry );
if ( ! isShallowEqual( mapResult, secondMapResult ) ) {
// eslint-disable-next-line no-console
console.warn(
`The 'useSelect' hook returns different values when called with the same state and parameters. This can lead to unnecessary rerenders.`
);
warnOnUnstableReference( mapResult, secondMapResult );
didWarnUnstableReference = true;
}
}
Expand Down

0 comments on commit 6ab4c36

Please sign in to comment.