@wordpress/data package is WordPress’s centralized state management system, built on Redux principles. It provides a powerful way to manage application state, fetch data from REST APIs, and share data between components.
Overview
WordPress’s data module serves as a hub to manage application state for both plugins and WordPress itself. It provides tools to manage data within and between distinct modules, scalable from simple plugins to complex single-page applications.The data module is built upon Redux but includes unique features like resolvers, normalized selectors, and built-in async handling that distinguish it from standard Redux implementations.
Installation
Install the package using npm:Core Concepts
Stores
A store is a centralized container for your application’s state. WordPress core provides several built-in stores:core- Core data entities (posts, pages, users)core/editor- Editor-specific statecore/block-editor- Block editor statecore/notices- User notifications
Selectors
Selectors are functions that retrieve and derive state values. They’re your primary mechanism for reading data:Actions
Actions are functions that modify state. Dispatching actions is the primary mechanism for making changes:Resolvers
Resolvers are side-effects for selectors. When a selector is called for the first time, its resolver fetches the required data:Using Data in React Components
useSelect Hook
TheuseSelect hook retrieves data from stores and automatically re-renders your component when the data changes:
useDispatch Hook
TheuseDispatch hook provides access to action creators:
Combining useSelect and useDispatch
For complex components, combine both hooks:Checking Resolution Status
Use resolution selectors to track async operations:- hasFinishedResolution
- isResolving
Critical: Always pass identical arguments to both the selector and resolution check functions. Store them in a variable to avoid typos:
Creating Custom Stores
Create your own store for custom data:Registry Selectors
Create selectors that can access other stores:Performance Optimization
Batch Updates
Useregistry.batch() to group multiple updates and trigger listeners once:
Memoized Selectors
UsecreateSelector for expensive computations:
Common Patterns
Loading States
Optimistic Updates
Best Practices
- Use dependencies correctly: Always include external variables in
useSelectdependencies - Avoid over-selecting: Only select the data you need to minimize re-renders
- Handle loading states: Always check resolution status before rendering data
- Use batch for multiple updates: Group related state changes together
- Leverage caching: Resolvers cache responses automatically - take advantage of this
Next Steps
- Explore Filters and Hooks for extending functionality
- Learn about Editor Customization
- Read the @wordpress/data package documentation