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
  • Loading branch information
Mamaduka committed Dec 8, 2024
1 parent 7cf1ced commit 9f92c5e
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 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,23 @@ import useAsyncMode from '../async-mode-provider/use-async-mode';

const renderQueue = createQueue();

function warnOnUnstableReference( a, b ) {
let keys = [];
if ( a.constructor === Object && b.constructor === Object ) {
keys = Object.keys( a ).filter( ( k ) => a[ k ] !== b[ k ] );
} else if ( Array.isArray( a ) && Array.isArray( b ) ) {
keys = [ ...a.keys() ].filter( ( i ) => a[ i ] !== b[ i ] );
}

// 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 +176,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 9f92c5e

Please sign in to comment.