When working with Gutenberg blocks, accessing WordPress data efficiently is essential. One of the most commonly used tools for this is select('core').
In this guide, weโll break it down in a simple and practical way, with examples you can use immediately.
๐ What is select('core')?
In Gutenberg:
select()is used to read data from a data store'core'refers to the WordPress core data store- It allows you to fetch:
- Posts
- Pages
- Users
- Taxonomies
- Media
๐ In simple terms:
select('core')lets you fetch data from WordPress (via REST API) inside your block.
โ ๏ธ Basic Example (Not Recommended for UI)
import { select } from '@wordpress/data';
const posts = select('core').getEntityRecords('postType', 'post');
โ Why this is not ideal?
- It is not reactive
- UI will not update automatically
- Should not be used inside React render logic
โ
Correct Way: Using useSelect
The recommended approach in Gutenberg is using the useSelect hook.
๐ฏ Example: Fetch Posts
import { useSelect } from '@wordpress/data';
const posts = useSelect((select) => {
return select('core').getEntityRecords('postType', 'post');
}, []);
๐พ Storing Data in a Variable & Using It
Hereโs a simple working example:
import { useSelect } from '@wordpress/data';
export default function MyComponent() {
const posts = useSelect((select) => {
return select('core').getEntityRecords('postType', 'post');
}, []);
if (!posts) {
return 'Loading...';
}
return (
<ul>
{posts.map((post) => (
<li key={post.id}>
{post.title.rendered}
</li>
))}
</ul>
);
}
๐ Whatโs Happening Here?
useSelect()subscribes to the data storepostsvariable stores fetched data- Initially, it returns
nullโ then updates with real data - Component re-renders automatically when data is available
โก Using Query Parameters (Best Practice)
To improve performance, always limit the data you fetch:
const posts = useSelect((select) => {
return select('core').getEntityRecords('postType', 'post', {
per_page: 5,
_fields: ['id', 'title'],
});
}, []);
โ Benefits:
- Faster API response
- Less memory usage
- Cleaner data
๐ Advanced Pattern (Loading State Handling)
const { posts, isLoading } = useSelect((select) => {
const query = { per_page: 5 };
return {
posts: select('core').getEntityRecords('postType', 'post', query),
isLoading: !select('core').hasFinishedResolution(
'getEntityRecords',
['postType', 'post', query]
),
};
}, []);
๐ง Why this is important?
- Helps handle loading state properly
- Prevents UI flickering
- Useful for production-grade blocks