@wordpress/data package provides a centralized data layer for managing application state. Itβs built on Redux principles with additional features like selectors, resolvers, and action creators.
Installation
Core Concepts
The data module organizes state into separate stores. Each store contains:- Reducer - Manages state changes
- Actions - Trigger state updates
- Selectors - Retrieve data from state
- Resolvers - Fetch async data
Creating a Store
Basic Store
With Async Resolvers
Using Stores
select - Read Data
dispatch - Update Data
subscribe - Watch Changes
React Hooks
useSelect
Retrieve data from stores.useDispatch
Access action creators.Combined Pattern
Advanced Selectors
Registry Selectors
Access other stores from selectors.Memoized Selectors
Async Operations
Using Resolvers
Resolvers automatically fetch data when selectors are called:Check Resolution Status
resolveSelect
Wait for resolution to complete:Batching Updates
Batch multiple actions to reduce re-renders:Higher-Order Components
withSelect
Inject store data as props.withDispatch
Inject action creators as props.Custom Registries
Create isolated registries for testing or specific contexts:Persistence
Local Storage Persistence
Debugging
DevTools
Enable Redux DevTools:Log State Changes
TypeScript Support
The package includes TypeScript definitions:Best Practices
- Normalize State - Store entities in flat objects by ID
- Use Selectors - Never access state directly
- Memoize Expensive Selectors - Use
createSelectorfor computed values - Batch Related Updates - Use
registry.batch()for multiple actions - Handle Loading States - Check resolution status in components
Core WordPress Stores
WordPress provides several built-in stores:core- Settings and entitiescore/blocks- Block typescore/block-editor- Block editor statecore/editor- Post editor statecore/edit-post- Edit post UI state