Skip to main content
The @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

The compose 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 use compose to combine multiple HOCs:

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:
Make sure you have React 18.0.0 or higher installed in your project.

API Reference

For complete API documentation of all hooks and HOCs, visit the GitHub repository.