Zustand Computed State Middleware is a lightweight utility designed to seamlessly integrate derived or computed state into Zustand stores. It enables developers to define functions that calculate new state values based on the existing store state, automatically merging these computed values back into the primary store. This allows computed properties to be accessed directly alongside regular state, simplifying state management logic. The current stable version of this specific middleware is 0.1.3, representing an initial release focused on core functionality and ease of use. However, a different package with similar functionality, `zustand-computed`, is at version 2.1.1 and has seen more active development and breaking changes. As a middleware, its release cadence will likely follow its parent library, Zustand, or be driven by feature enhancements and bug fixes. A key differentiator is its 'dead simple' approach, providing direct state augmentation without the need for manual selectors in many cases, though it explicitly advises keeping computed functions light due to their re-evaluation on every state change to prevent performance bottlenecks. It ships with full TypeScript support, requiring explicit type definitions for robust usage.
npm install zustand-middleware-computed-stateVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to create a Zustand store with computed state using the middleware and use it in a React component, showcasing basic increment and derived values.
Profile your application to identify expensive computed functions. Consider optimizing their logic or, for specific use cases, using Zustand's built-in selectors with memoization (`useCallback`) if a computed value is only needed in particular components and doesn't need to be part of the global store.
Refer to the TypeScript example in the package's README, ensuring your `create` function correctly applies generics like `create<CombinedStore>(computed<Store, ComputedStore>(...))`.
Consider migrating to the more actively maintained `zustand-computed` package if you require recent features or bug fixes, being mindful of the API changes, specifically the move from `computed` to `createComputed` in its v2.0.0 release.
Ensure you are using the named import `import { create } from 'zustand'` for modern Zustand versions. If you are in a CommonJS environment, check your bundler configuration to correctly handle ESM modules.Define a `CombinedStore` type that merges your base store and computed store types (e.g., `type CombinedStore = BaseStore & ComputedStore;`). Then, pass this `CombinedStore` type as a generic to Zustand's `create` function: `create<CombinedStore>(...)`.