@wordpress/compose package provides a collection of handy React Hooks and Higher Order Components (HOCs) you can use to wrap your WordPress components and provide basic features like state management, instance IDs, and more.
Installation
Install the package using npm:This package assumes that your code will run in an ES2015+ environment. If you’re using an environment with limited support for such language features, include the polyfill shipped in
@wordpress/babel-preset-default.The compose Function
Thecompose function is inspired by lodash’s flowRight and allows you to compose any number of functions. It executes the last function first, then sequentially moves back through the previous functions, passing the result upward.
Think of it as layering functions - each function wraps the result of the next:
Example: Using compose
Here’s how you can usecompose to combine multiple HOCs:
Popular Hooks
useInstanceId
Provides a unique instance ID for component instances:useDebounce
Debounces a function similar to Lodash’s debounce:useFocusOnMount
Determines focus behavior when an element mounts:useMediaQuery
Runs a media query and returns its value:useRefEffect
Effect-like ref callback that allows cleanup:Essential Hooks
useInstanceId
Generate unique IDs for component instances
useDebounce
Debounce function calls to improve performance
useMediaQuery
Responsive design with media query detection
useFocusOnMount
Control focus behavior when components mount
useRefEffect
Ref callbacks with cleanup capabilities
useResizeObserver
Observe element size changes
useMergeRefs
Combine multiple refs into one callback
usePrevious
Access previous render values
Higher Order Components
withInstanceId
Provides a unique instance ID via props:ifCondition
Renders a component only if a condition is satisfied:Utility Functions
createHigherOrderComponent
Creates a higher-order component with a generated display name:debounce
Creates a debounced function:throttle
Creates a throttled function:Peer Dependencies
This package requires React as a peer dependency:API Reference
For complete API documentation of all hooks and HOCs, visit the GitHub repository.Related Packages
@wordpress/element- React abstraction layer@wordpress/components- UI components that use these hooks@wordpress/data- Data management layer