useSelect
is a React React is a JavaScript library that makes it easy to reason about, construct, and maintain stateless and stateful user interfaces. https://reactjs.org/. hook that lets you subscribe to WordPress data in the block Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. editor. It checks if consumed data has changed and then rerenders your components accordingly.
Usually, things just work, and consumers don’t have to worry about unnecessary rerenders. However, sometimes data is directly manipulated in the mapSelect
callback, which can mislead the useSelect
hook into thinking that the data has changed when it has not.
Example:
export function ExampleWithWarning() {
const { nameAndIds } = useSelect( function mapSelect( select ) {
const authors = select( 'core' ).getUsers( {
who: 'authors',
context: 'view',
} );
return {
// `Array.map` will return a new array for every call,
// even if the data is the same.
nameAndIds: authors?.map( ( { id, name } ) => ( { id, name } ) ),
};
}, [] );
return <>{ /* Your rendering logic here */ }</>;
}
WordPress will now display a warning when SCRIPT_DEBUG
is enabled to help consumers identify possible performance bottlenecks.
Example warning:
The useSelect
hook returns different values when called with the same state and parameters. This can lead to unnecessary re-renders and performance issues if not fixed.
Non-equal value keys: nameAndIds
This warning can be fixed by requesting only the values needed to render a component or moving data manipulation outside the mapSelect
callback. The actual solution can vary based on your code and logic.
Please refer to the fantastic article “How to work effectively with the useSelect hook” to learn more about best practices for using the useSelect
hook.
Here’s how I would fix the example code from this post:
export function ExampleFixed() {
const { nameAndIds } = useSelect( function mapSelect( select ) {
const authors = select( 'core' ).getUsers( {
who: 'authors',
context: 'view',
// Requests only fields that are needed.
_fields: 'id,name',
} );
return {
nameAndIds: authors,
};
}, [] );
return <>{ /* Your rendering logic here */ }</>;
}
Props to @kirasong for the review.
#6-8, #dev-notes, #dev-notes-6-8, #editor